Python Data Structures
Lists
A variable that stores more than one item, enclosed in square brackets.
Subscripting
list = ["a", "b", "c"]
list[0] # starts counting from left
>> "a"
list[-1] # starts counting from right
>> "c"Editing items
list = ["a", "b", "c"]
list[0] = "b"
list = ["b", "b", "c"]Merging lists
list_a = ["apple", "apricot"]
list_b = ["banana", "blue"]
list_c = list_a + list_b
print(list_c)
>> ["apple", "apricot", "banana", "blue"]Nesting lists
list_a = ["apple", "apricot"]
list_b = ["banana", "blue"]
list_c = [list_a, list_b]
print(list_c)
>> [["apple", "apricot"], ["banana", "blue"]]Adding single items
list = ["a", "b"]
list.append("c")
print(list)
>> ["a", "b", "c"]Adding multiple items
list = ["a", "b"]
list.extend(["c", "d"])
# OR
list += ["c", "d"]
print(list)
>> ["a", "b", "c", "d"]Removing items
list = ["a", "b"]
list.remove("a")
print(list)
>> ["b"]Finding index
list.index(item, start_index)
list = ["a", "b", "c", "a"]
list.index("a") # gives 0
list.index("a", 1) # gives 3Joining items of a list
"__".join()
list = ["a", "b", "c"]
"and".join(list)
>> "aandbandc"
# or use for loop and string concatenationAdding dicts to a list
list = [{"key": "value"}]
dict = {"key2": "value2"}
list.append(dict)
# Can't use list += dict, this only adds the key of the dictionarypop()
a = ['a', 'b', 'c', 'd']
a.pop(1)
>> ['a', 'c', 'd']
a.pop() # removes the last itemDictionaries
Key–Value pairs.
Made up of {Key: Value} pairs
dict = {"name": "elkan", "age": "19"}Uses curly brackets. Can have multiple items, separated by ,. Each key can only have one value.
Formatting your code
dict = {
"name": "elkan",
"age": "19",
}Retrieving items
# allowed
dict = {"name": "elkan"}
print(dict["name"])
# allowed
dict = {123: "elkan"}
print(dict[123])
# not allowed
dict = {name: "elkan"}
print(dict[name])
# using key and get()
dict["name"] = "elkan"
dict["abc"] # gives you a KeyError because no such key exists
dict.get("abc", "Does not exist") # if abc does not exist, it prints "Does not exist"Adding new items
dict = {"name": "elkan"}
dict["age"] = "19"Editing entries
dict = {"name": "elkan"}
dict["name"] = "chloe"Empty dict / wiping
dict = {}Looping through a dict
dict = {
"one": "value one",
"two": "value two",
"three": "value three",
}
for key in dict:
print(key)
# if not specified keys or values, it takes the key
# output gives the keys: one, two, three
for key in dict.keys():
print(key)
for value in dict.values():
print(value)
for key, value in dict.items():
print(key)
print(value)Replace nested ifs with a dict lookup
# instead of
def calculate(n1, n2):
if a == this:
hello
if a == that:
bye
if a == there:
fat
# do this instead
calculate = {
"this": "hello",
"that": "bye",
"there": "fat",
}Functions in dictionaries
def add(n1, n2):
return n1 + n2
calculate = {
"+": add
}
function = calculate["+"]
function(2, 3) # gives 5
# function becomes add, and add(2, 3) returns 5.
# don't need the add() or add(n1, n2)Deleting items
dict = {
"a": "one",
"b": "two",
}
del dict["a"]Random choice from a dict
dict = {
"a": "one",
"b": "two",
}
# To get a / b
random.choice(list(dict.keys()))
>> "a"
# To get one / two
random.choice(list(dict.values()))
>> "one"
# To get key and value
random.choice(list(dict.items()))
>> ("a", "one")Tuples
Can’t change its values (immutable).
Creating
my_tuple = (1, 3, 8)Converting tuple to list
tuple = (1, 3, 8)
list(tuple)Slicing
Splitting up a list / tuple.
Splitting
list = ["a", "b", "c", "d", "e", "f", "g"]
print(list[2:5])
>>> ["c", "d", "e"]
print(list[2:])
>>> ["c", "d", "e", "f", "g"]
# View the numbers as lines between each item.
# | "a" | "b" | "c" | "d" | "e" | "f" | "g" |
0 1 2 3 4 5 6 7Splitting with increments
list = ["a", "b", "c", "d", "e", "f", "g"]
print(list[2:5:2])
>>> ["c", "e"]
# The third number is increment. It gives every 2nd item.
print(list[::2])
>>> ["a", "c", "e", "g"]Negative increments
list = ["a", "b", "c", "d", "e", "f", "g"]
print(list[::-1])
>>> ["g", "f", "e", "d", "c", "b", "a"]
# Negative increments reverse the listSlicing inside a for loop
list = ["a", "b", "c", "d", "e", "f", "g"]
for item in list[1:]:
...See next
- Python-Control-Flow — iterating over these structures
- Python-Functions — passing them as arguments
- Python-NumPy — the high-performance array equivalent