my_list = ["a", 1, "b", 2]
my_list[0]'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:
my_list = ["a", 1, "b", 2]
my_list[0]'a'
Indexing to mutate values:
my_list[0] = 5
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:
my_tuple = ("a", 1, "b", 2)
my_tuple[0]'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:
my_dict = {"banana": 10, "apple": 3, "orange": 40}
my_dict["banana"]10
Use key to add key: value pairs:
my_dict["pear"] = 5
my_dict{'banana': 10, 'apple': 3, 'orange': 40, 'pear': 5}
Use key to mutate value associated with key:
my_dict["pear"] += 5
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)
my_list = [3, 5, 5]
for value in my_list:
print(value)3
5
5
my_tuple = (3, 5, 5)
for value in my_tuple:
print(value)3
5
5
my_set = {3, 2, 1, 30, 4}
for value in my_set:
print(value)1
2
3
4
30
my_dictionary = {3: "a", 5: "b"}
for key in my_dictionary:
print(key)3
5
You can change values in a dictionary with for key in dictionary
my_dictionary = {"a": 2, "b": 3}
for key in my_dictionary:
my_dictionary[key] += 1
my_dictionary{'a': 3, 'b': 4}
Use for x in data_structure.method() for dictionaries
my_dictionary = {3: "a", 5: "b"}
for value in my_dictionary.values():
print(value)a
b
my_dictionary = {3: "a", 5: "b"}
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:
my_list = [2, 3, 1, 2]
for value in my_list:
my_list.remove(value)
my_list[3, 2]
Infinite loop:
my_list = [2, 3, 1, 2]
for value in my_list:
my_list.append(value + 1) # this causes an infinite loopError:
my_dict = {2: 0, 3: 1, 1: 0}
for key in my_dict:
my_dict.pop(key) # this causes an errorError:
my_set = {2, 1, 4, 5, 7, 10, 23, 44}
for value in my_set:
my_set.discard(value) # this causes an error