= ["a", 1, "b", 2]
my_list 0] my_list[
'a'
Here are the four data structures that we’ve worked with in Python:
[]
) syntax for creating a list0
) with square brackets ([]
) as wellIndexing to retrieve values:
= ["a", 1, "b", 2]
my_list 0] my_list[
'a'
Indexing to mutate values:
0] = 5
my_list[ my_list
[5, 1, 'b', 2]
.append(value)
.insert(index, value)
.pop(index)
.remove(value)
()
) syntax for creating a tuple0
) with square brackets ([]
)Indexing to retrieve values:
= ("a", 1, "b", 2)
my_tuple 0] my_tuple[
'a'
Not possible to mutate/change values in tuples
No methods to change it (because tuples are immutable)
key: value
{}
) with key and value separated by colon (:
)[]
)Use key to retrieve values:
= {"banana": 10, "apple": 3, "orange": 40}
my_dict "banana"] my_dict[
10
Use key to add key: value
pairs:
"pear"] = 5
my_dict[ my_dict
{'banana': 10, 'apple': 3, 'orange': 40, 'pear': 5}
Use key to mutate value associated with key:
"pear"] += 5
my_dict[ my_dict
{'banana': 10, 'apple': 3, 'orange': 40, 'pear': 10}
.values()
.items()
.pop()
for x in set
to iterate over the elements in a set.add(value)
adds an element to the set.discard(value)
discards the specified valueYou can also use the operator in
and the function len()
with sets
Use the function set()
to convert a list to a set, and list()
to convert a set into a list
Use for x in data_structure
to retrieve values/keys (cannot make changes with this type of loop)
= [3, 5, 5]
my_list for value in my_list:
print(value)
3
5
5
= (3, 5, 5)
my_tuple for value in my_tuple:
print(value)
3
5
5
= {3, 2, 1, 30, 4}
my_set for value in my_set:
print(value)
1
2
3
4
30
= {3: "a", 5: "b"}
my_dictionary for key in my_dictionary:
print(key)
3
5
You can change values in a dictionary with for key in dictionary
= {"a": 2, "b": 3}
my_dictionary for key in my_dictionary:
+= 1
my_dictionary[key] my_dictionary
{'a': 3, 'b': 4}
Use for x in data_structure.method()
for dictionaries
= {3: "a", 5: "b"}
my_dictionary for value in my_dictionary.values():
print(value)
a
b
= {3: "a", 5: "b"}
my_dictionary for key, value in my_dictionary.items():
print(value)
print(key)
a
3
b
5
It is not possible to remove or add items to a list, a dictionary, or a set inside a for x in data_structure
loop. This is what happens when you try to do so:
Weird behavior:
= [2, 3, 1, 2]
my_list for value in my_list:
my_list.remove(value) my_list
[3, 2]
Infinite loop:
= [2, 3, 1, 2]
my_list for value in my_list:
+ 1) # this causes an infinite loop my_list.append(value
Error:
= {2: 0, 3: 1, 1: 0}
my_dict for key in my_dict:
# this causes an error my_dict.pop(key)
Error:
= {2, 1, 4, 5, 7, 10, 23, 44}
my_set for value in my_set:
# this causes an error my_set.discard(value)