Among the many data structures in Python, lists and dictionaries are perhaps the most common, this might be because of their versatility, truth is that we can use these structures in many different and powerful ways to represent many kinds of data.

Lists, as the name implies, are ordered collections of data that can be accessed by index, unlike with other programming languages such as Javascript, the data does not need to be of the same data type, this means that we can have lists that contain strings, integers, floats, and even other lists or dictionaries.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# Define a list of colors
colors = ['red', 'green', 'blue', 'yellow', 'orange', 'purple']

# We can print these values one by one by iterating over the list
print('=== Iterating over the list ===')
for color in colors:
    print(color)

# But we can also print just one of them by referencing the index
print('=== Printing one of the colors by referencing the index ===')
print(colors[2])

# Lists, just like vectors or arrays in other languages, start on index 0
# So the first color is at index 0, the second at index 1, etc.

# But we also can add more colors to the list
colors.append('black')
print('=== Printing the list after adding a color ===')
print(colors)

Result:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
=== Iterating over the list ===
red
green
blue
yellow
orange
purple
=== Printing one of the colors by referencing the index ===
blue
=== Printing the list after adding a color ===
['red', 'green', 'blue', 'yellow', 'orange', 'purple', 'black']

We can also pick a random color from the list by referencing the index

1
2
3
4
5
# Let's play a little and print a color at random
from random import randrange
random_index = randrange(0, len(colors))
print('=== Printing a random color ===')
print(colors[random_index])

Result:

1
2
=== Printing a random color ===
blue

In the previous example we used the len() function, this gets the length of an iterable item and returns an int value. There are many more methods we can apply to lists, but for now we will focus on the most common ones. If you want to learn more about the methods available to you, you can check out the documentation for the list class in Python or use the dir() function to see what methods are available to you.

1
2
3
# Let's find our the methods of the list class
print('=== List methods ===')
print(dir(colors))

Result:

1
2
=== List methods ===
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

As mentioned earlier, we can add different types of data to a list using the append() method, this will add the data to the end of the list.

1
2
3
4
5
6
7
# Define a mixed list
mixed_list = [1, 'two', 3.0, 'four', 5, 'six', 7.0, 'eight', 9, ['ten', 11, 12.0]]

# Add a new item to the end of the list
mixed_list.append('thirteen')
print('=== Printing the mixed list after adding a new item ===')
print(mixed_list)

Result:

1
2
=== Printing the mixed list after adding a new item ===
[1, 'two', 3.0, 'four', 5, 'six', 7.0, 'eight', 9, ['ten', 11, 12.0], 'thirteen']

And, as we can see in the output of the dir() function, we can also sort the list using the sort() method, reverse the order of the list using the reverse() method, and remove items from the list using the remove() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Let's sort our colors list
colors.sort()
print('=== Printing the sorted colors list ===')
print(colors)

# But then we can reverse it
colors.reverse()
print('=== Printing the reversed colors list ===')
print(colors)

# And we can remove the last item
colors.pop()
print('=== Printing the colors list after removing the last item ===')
print(colors)

Result:

1
2
3
4
5
6
=== Printing the sorted colors list ===
['black', 'blue', 'green', 'orange', 'purple', 'red', 'yellow']
=== Printing the reversed colors list ===
['yellow', 'red', 'purple', 'orange', 'green', 'blue', 'black']
=== Printing the colors list after removing the last item ===
['yellow', 'red', 'purple', 'orange', 'green', 'blue']

Similar to lists, dictionaries are also ordered collections of data, but unlike lists, the data in a dictionary is accessed by key, which is a unique identifier for each piece of data, and normally they reference a single item in a collection, this can represent a row in a database or an entry in a set of data, this means that if you need to define a list of objects you will technically have a list of dictionaries (which can themselves contain other lists).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Let's define a dictionary representing a schedule, with the day of the week as key and the activity as value.
schedule = {
    'Monday': 'Go to the gym',
    'Tuesday': 'Do some coding',
    'Wednesday': 'Go to the gym',
    'Thursday': 'Do some coding',
    'Friday': 'Go to the gym',
    'Saturday': 'Do some coding',
    'Sunday': 'Go to the gym'
}

print('=== Printing the schedule ===')
print(schedule)

Result:

1
2
=== Printing the schedule ===
{'Monday': 'Go to the gym', 'Tuesday': 'Do some coding', 'Wednesday': 'Go to the gym', 'Thursday': 'Do some coding', 'Friday': 'Go to the gym', 'Saturday': 'Do some coding', 'Sunday': 'Go to the gym'}

As shown in the code above, a dictionary is typically used to represent a set of data that is related to a single item, for example, a user profile, or a list of items that are related to a single object. But what happens if we want to define several objects that are related to each other, for example, a list of users, or a list of items that are related to a single user? We can define a list of dictionaries, where each dictionary contains data that is related to a single object, being able to access a single dictionary by the list index and then access the data in the dictionary using the key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# We'll define a list of schedules to represent several users
schedules = [
    {
        'Monday': 'compress',
        'Tuesday': 'program',
        'Wednesday': 'input',
        'Thursday': 'parse',
        'Friday': 'connect',
        'Saturday': 'hack',
        'Sunday': 'calculatem'
    },
    {
        'Monday': 'copy',
        'Tuesday': 'navigate',
        'Wednesday': 'bypass',
        'Thursday': 'synthesize',
        'Friday': 'synthesize',
        'Saturday': 'navigate',
        'Sunday': 'synthesizem'
    },
    {
        'Monday': 'synthesize',
        'Tuesday': 'generate',
        'Wednesday': 'transmit',
        'Thursday': 'copy',
        'Friday': 'hack',
        'Saturday': 'navigate',
        'Sunday': 'program'
    }
]

# Then we can iterate over the list of schedules and print the schedule for each user
print('=== Iterating over the list of schedules ===')
for index, schedule in enumerate(schedules):
    print(f"""
    Schedule for user {index}:
    {schedule}
    {'-'*50}
        """)

Result:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
=== Iterating over the list of schedules ===

Schedule for user 0:
{'Monday': 'compress', 'Tuesday': 'program', 'Wednesday': 'input', 'Thursday': 'parse', 'Friday': 'connect', 'Saturday': 'hack', 'Sunday': 'calculatem'}
--------------------------------------------------


Schedule for user 1:
{'Monday': 'copy', 'Tuesday': 'navigate', 'Wednesday': 'bypass', 'Thursday': 'synthesize', 'Friday': 'synthesize', 'Saturday': 'navigate', 'Sunday': 'synthesizem'}
--------------------------------------------------


Schedule for user 2:
{'Monday': 'synthesize', 'Tuesday': 'generate', 'Wednesday': 'transmit', 'Thursday': 'copy', 'Friday': 'hack', 'Saturday': 'navigate', 'Sunday': 'program'}
--------------------------------------------------

That's so cool, isn't it? But what happens if we want a specific piece of data from a dictionary? We can specify the key we want to access using the [] operator, and the value of the key will be returned. To do this we can either iterate over the list or define an index for the item we want to access, for example, the user profile of the first user in the list.

1
2
3
4
5
6
7
# Get the schedule for the first user for Wednesday
print('=== Getting the schedule for the first user for Wednesday ===')
print(schedules[0]['Wednesday'])

# Get the schedule for the second user for Thursday
print('=== Getting the schedule for the second user for Thursday ===')
print(schedules[1]['Thursday'])

Result:

1
2
3
4
=== Getting the schedule for the first user for Wednesday ===
input
=== Getting the schedule for the second user for Thursday ===
synthesize

Remember, every item in Python has a list of methods available to it, we can use the dir() function to see what methods are available to us.

1
2
3
# Print the method names of the dictionary class
print('=== Dictionary methods ===')
print(dir(schedule))

Result:

1
2
=== Dictionary methods ===
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Now let's play a little, we'll iterate over the list and print the activity for each day of the week
print('=== Iterating over the list of schedules ===')
for index, schedule in enumerate(schedules):
    print(f"""
    Schedule for user {index}:
    Monday: {schedule['Monday']}
    Tuesday: {schedule['Tuesday']}
    Wednesday: {schedule['Wednesday']}
    Thursday: {schedule['Thursday']}
    Friday: {schedule['Friday']}
    Saturday: {schedule['Saturday']}
    Sunday: {schedule['Sunday']}
    {'-'*50}
    """)

Result:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
=== Iterating over the list of schedules ===

Schedule for user 0:
Monday: compress
Tuesday: program
Wednesday: input
Thursday: parse
Friday: connect
Saturday: hack
Sunday: calculatem
--------------------------------------------------


Schedule for user 1:
Monday: copy
Tuesday: navigate
Wednesday: bypass
Thursday: synthesize
Friday: synthesize
Saturday: navigate
Sunday: synthesizem
--------------------------------------------------


Schedule for user 2:
Monday: synthesize
Tuesday: generate
Wednesday: transmit
Thursday: copy
Friday: hack
Saturday: navigate
Sunday: program
--------------------------------------------------