Data Structures - CameronAuler/python-devops GitHub Wiki
Table of Contents
Lists
A list is a mutable, ordered collection that allows duplicate elements.
List Definition
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "apple", 3.14, True]
print(fruits)
# Output:
['apple', 'banana', 'cherry']
Indexing & Slicing
fruits = ["apple", "banana", "cherry", "date"]
# Access elements by index
print(fruits[0]) # First element
print(fruits[-1]) # Last element
# Slice the list
print(fruits[1:3]) # Elements at index 1 to 2
print(fruits[:2]) # First two elements
print(fruits[2:]) # All elements from index 2
# Output:
apple
date
['banana', 'cherry']
['apple', 'banana']
['cherry', 'date']
List Methods
# append() - Adds an element to the end of the list
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
# clear() - Removes all elements from the list
fruits.clear()
# copy() - Returns a shallow copy of the list
fruits = ["apple", "banana", "cherry"]
new_list = fruits.copy()
# count() - Counts occurrences of an element
fruits = ["apple", "banana", "apple", "cherry"]
count = fruits.count("apple")
# extend() - Extends the list by appending elements from another iterable
fruits = ["apple", "banana"]
fruits.extend(["cherry", "date"])
# index() - Returns the index of the first occurrence of an element
index = fruits.index("banana")
# insert() - Inserts an element at a specified index
fruits.insert(1, "blueberry")
# pop() - Removes and returns the element at the specified index (default is the last)
popped = fruits.pop()
# remove() - Removes the first occurrence of an element
fruits.remove("banana")
# reverse() - Reverses the elements of the list
fruits.reverse()
# sort() - Sorts the list in ascending order
fruits.sort()
# sort(reverse=True) - Sorts the list in descending order
fruits.sort(reverse=True)
# Output for append():
['apple', 'banana', 'cherry', 'date']
# Output for clear():
[]
# Output for copy():
['apple', 'banana', 'cherry']
# Output for count():
2
# Output for extend():
['apple', 'banana', 'cherry', 'date']
# Output for index():
1
# Output for insert():
['apple', 'blueberry', 'banana', 'cherry', 'date']
# Output for pop():
'cherry'
['apple', 'blueberry', 'banana', 'date']
# Output for remove():
['apple', 'blueberry', 'cherry', 'date']
# Output for reverse():
['date', 'cherry', 'blueberry', 'apple']
# Output for sort():
['apple', 'blueberry', 'cherry', 'date']
# Output for sort(reverse=True):
['date', 'cherry', 'blueberry', 'apple']
Tuples
A tuple is an immutable, ordered collection that allows duplicate elements.
Tuple Definition
# Creating tuples
fruits = ("apple", "banana", "cherry")
numbers = (1, 2, 3, 4)
print(fruits)
# Output:
('apple', 'banana', 'cherry')
Accessing Elements
# Indexing and slicing work similarly to lists
print(fruits[0]) # First element
print(fruits[-1]) # Last element
print(fruits[1:3])# Slicing
# Output:
apple
cherry
('banana', 'cherry')
Immutability
Tuples cannot be modified after creation.
fruits[0] = "orange" # Attempts to replace the first item of the tuple with "orange", Raises a TypeError
Dictionaries
A dictionary is an unordered collection of key-value pairs, where keys are unique.
Dictionary Definition
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person)
# Output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing & Modifying
# Accessing values by key
print(person["name"]) # Access value
print(person.get("age")) # Safe access (returns None if key doesn't exist)
# Modifying values
person["age"] = 31 # Update value
person["job"] = "Engineer" # Add new key-value pair
# Output:
Alice
30
Dictionary Methods
# clear() - Removes all elements from the dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
person.clear()
# copy() - Returns a shallow copy of the dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
new_person = person.copy()
# fromkeys() - Creates a new dictionary with specified keys and a single value
keys = ["name", "age", "city"]
default_dict = dict.fromkeys(keys, "Unknown")
# get() - Returns the value for a specified key, or a default if the key is not found
value = person.get("name")
missing_value = person.get("job", "Not Found")
# items() - Returns a view object of key-value pairs
items = person.items()
# keys() - Returns a view object of all keys
keys = person.keys()
# pop() - Removes a key and returns its value
age = person.pop("age")
# popitem() - Removes and returns the last inserted key-value pair
last_item = person.popitem()
# setdefault() - Returns the value of a key, or sets it to a default if it doesn't exist
job = person.setdefault("job", "Engineer")
# update() - Updates the dictionary with key-value pairs from another dictionary or iterable
person.update({"age": 31, "city": "San Francisco"})
# values() - Returns a view object of all values
values = person.values()
# Output for clear():
{}
# Output for copy():
{'name': 'Alice', 'age': 30, 'city': 'New York'}
# Output for fromkeys():
{'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
# Output for get():
Alice
Not Found
# Output for items():
dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
# Output for keys():
dict_keys(['name', 'age', 'city'])
# Output for pop():
30
{'name': 'Alice', 'city': 'New York'}
# Output for popitem():
('city', 'New York')
{'name': 'Alice'}
# Output for setdefault():
Engineer
{'name': 'Alice', 'job': 'Engineer'}
# Output for update():
{'name': 'Alice', 'job': 'Engineer', 'age': 31, 'city': 'San Francisco'}
# Output for values():
dict_values(['Alice', 'Engineer', 31, 'San Francisco'])
Sets
A set is an unordered collection of unique elements.
Set Definition
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 4, 4]) # Removes duplicates
print(fruits)
print(numbers)
# Output:
{'banana', 'cherry', 'apple'}
{1, 2, 3, 4}
Set Operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Combine elements
# Intersection
print(set1 & set2) # Common elements
# Difference
print(set1 - set2) # Elements in set1 but not in set2
# Symmetric Difference
print(set1 ^ set2) # Elements in either set, but not both
# Output:
{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
Set Modification
fruits = {"apple", "banana"}
fruits.add("cherry") # Add element
fruits.update(["date", "fig"]) # Add multiple elements
fruits.remove("banana") # Remove element (raises KeyError if not found)
fruits.discard("pear") # Remove element (no error if not found)
fruits.clear() # Remove all elements
# Output:
{'apple', 'cherry', 'date', 'fig'}
{}