Getting started with Python lists and dictionaries
Introduction
Once you know how to create variables in Python, like my_variable = 3
, it is really useful to be able to store multiple items in a single variable. This is where lists and dictionaries come in. Lists and dictionaries are both data types in Python for storing collections of data.
Lists are defined with square brackets, and can hold multiple different elements which can either be the same type (e.g. all strings) or different types (e.g. a mix of strings, integers, booleans, etc.). A basic list creation statement is class_marks = [99, 68, 72, 50, 72]
.
Creating lists lets you carry out mathematical operations on the collection of data (like finding the average mark), iterate over the data to perform actions on each item (like add 5 to each mark), sort the data (e.g. from the lowest mark to the highest mark) and much more.
Dictionaries are defined with curly brackets, and hold key/value pairs. A basic dictionary creation statement is student_marks = {"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72}
.
Just like with lists, you can carry out mathematical operations on the data, iterate over it to perform actions, and sort the data. But with dictionaries, you can also associate specific values with specific keys, so in this case you could retrieve the mark of a particular student by using the key of their name.
The examples in this tutorial use short, manually-created lists and dictionaries, without huge amounts of data in them. But, bear in mind that:
- Lists and dictionaries can handle big amounts of data: A large part of why lists and dictionaries are so useful is that they can handle huge amounts of data, and provide efficient ways to manage and manipulate it. It is possible to import data from other sources (spreadsheets, text files, websites, etc.) directly into Python to feed your lists and dictionaries.
- Lists and dictionaries are made for loops! Another reason that lists and dictionaries are such an important thing to learn in Python, is that they go hand-in-hand with loops. Loops are a coding fundamental, and something we will focus on in the next tutorial in this series. Among many other things, loops let you iterate over the data in your lists and dictionaries and carry out complex operations on it. But before we can start on loops, we need to understand lists and dictionaries.
Read on to find out more about lists and dictionaries, and learn how to create and manipulate them in Python, with lots of examples provided.
Before you start
To complete the actions presented below, you must have:
- Installed Python on your machine
- Knowledge of how to execute Python commands and see their output, using for example either the Python Interactive Shell, a text editor and the terminal or another method such as Jupyter notebook
Lists
Creating and displaying lists
For the purposes of this tutorial, we'll imagine that we have a class of 5 students who have taken a test, and we want to use a list to hold the test results. Remember, Python knows to create a variable of list type when you use square brackets.
-
Use the following code to create an empty list. You can use either the Python Interactive Shell or save the code in a file using a text editor then execute it in the terminal as described in the previous tutorial:
class_marks = []
This creates an empty list to hold the class marks. Or, you could just skip straight to the next step and create the list with all its values in it.
-
Use the following code to create a list of class marks:
class_marks = [99, 68, 72, 50, 72]
-
Ask Python to display the list of marks with the following code:
class_marks
Accessing specific items in a list
Python lets us access specific items in a list by referring to their index position within the list.
The first item in a list is always at index position O. The second item is at index position 1, the third at position 3, and so on.
To access an item in a list, use the name of the list variable, followed by the index number of the item in square brackets.
-
Access the second item in the list of class marks with the following code:
class_marks[1]
Output:
68
Once you know how to access a list item, you can change its value. Let's imagine we realized we made a mistake, and the second class mark was actually 67, not 68.
-
Use the following code to change the second mark in the list:
class_marks[1] = 67
-
Display the list of class_marks, and see the following output:
[99, 67, 72, 50, 72]
There is another index that you can use to access items in a list, and this one works from right to left. The right-most item in a list has the index -1, then moving one to the left you have -2 and so on:
-
Access the last item in the list with the following code:
class_marks[-1]
Output:
72
Accessing a slice of the list
You can access a subsection of a list, or a slice of the list, by using square brackets with a colon. Before the colon, put the index position of the first item to return, and after the colon put the index position of the last item to return.
-
Use the following code to access the second, third, and fourth items in the list:
class_marks[1:4]
Output:
[68, 72, 50]
If you do not put a number after the colon, Python returns a slice of the list starting from the first index position you specify, including all the rest of the list to the end.
-
Use the following code to access a subsection of the list starting from the third item and going through to the end:
class_marks[2:]
Output:
[72, 50, 72]
If you do not put a number before the colon, Python returns a slice of the list starting from the beginning, and up to but not including the item at the index position after the colon.
-
Use the following code to access the subsection of the list starting from the beginning, up to but not including the item at index position 3:
class_marks[:3]
Output
[99, 68, 72]
Adding items to a list: append, extend, and insert
There are a number of different ways to add items to a list in Python, and we go over a few of them in this section.
The first, and most common, is the append()
method, which allows us to add an item to the end of the list.
-
Use the
append()
method to add a new mark of83
to the end of the list of marks, and ask Python to display the list of marks afterward:class_marks.append(83) class_marks
Output:
[99, 68, 72, 50, 72, 83]
Next, we have the
extend()
method, which allows us to add a new list of items to the end of the list. -
Use the
extend()
method to add two new marks of49
and55
to the end of the list of marks, and ask Python to display the list of marks afterward:class_marks.extend([49, 55]) class_marks
Output:
[99, 68, 72, 50, 72, 83, 49, 55]
Finally, the
insert()
method lets us insert a new item to a list in a specific index point. -
Use the
insert()
method to add a mark of30
at index position 1 (i.e. in second position in the list):class_marks.insert(1, 30) class_marks
Output:
[99, 30, 68, 72, 50, 72, 83, 49, 55]
Removing items from a list: remove, pop, and delete
Just as with adding items, there are multiple ways to remove items from lists too.
To remove a specific item from the list, we have the remove()
method.
Remember that our list of marks currently looks like the following: [99, 30, 68, 72, 50, 72, 83, 49, 55]
-
Use the
remove()
method to remove the mark of 68 from the list:class_marks.remove(68) class_marks
Output:
[99, 30, 72, 50, 72, 83, 49, 55]
Next, we have the
pop()
method, which removes the item at the specified index position: -
Use the
pop()
method to remove the first mark (99, at index position 0) from the list:class_marks.pop(0) class_marks
Output:
[30, 72, 50, 72, 83, 49, 55]
If we want to create a new variable with the "popped" item, we can do that too:
-
Use the
pop()
method to remove the third mark (50, at index position 2) and put it in a new variable:single_mark = class_marks.pop(2)
-
Use the following code to check the current values of
class_marks
andsingle_mark
:print(single_mark) print(class_marks)
Output:
50 [30, 72, 72, 83, 49, 55]
Finally, you can use the
del
keyword to delete an item at a specified index point, a slice of the list, or the complete list. -
Use the
del
keyword to delete the mark of 72 at index position 1:del class_marks[1] class_marks
Output
[30, 72, 83, 49, 55]
-
Use the
del
keyword to delete the slice of the list from index positions 0 (first item) up to but not including index position 2 (third item):del class_marks[0:2] class_marks
Output
[83, 49, 55]
Finally, we can use the
del
keyword to delete the whole list. Indeed, we can use it to delete any type of variable we want, so that Python forgets the variable completely. -
Use the
del
keyword to delete the list:del class_marks class_marks
Output:
NameError: name 'class_marks' is not defined
Python no longer remembers the variable, so our request to display it after deleting it returns an error.
Useful list operations
For the last section of our list tutorial, let's look at some useful operations that you might want to carry out on a list of data.
-
Recreate the
class_marks
variable as it originally was, to give us a base for the rest of this section:class_marks = [99, 68, 72, 50, 72]
-
Use the
sort()
method to sort the marks in the list into ascending order, then display the result:class_marks.sort() class_marks
Output:
[50, 68, 72, 72, 99]
-
Use the
sum()
method to get the sum of all marks in the list:sum(class_marks)
Output:
361
-
Use the
len()
method to get the length of the list, i.e. the total number of items in it:len(class_marks)
Output:
5
-
Use the
sum()
andlen()
methods together to calculate the average mark, and then display it:average_mark = sum(class_marks) / len(class_marks) average_mark
Output:
72.2
Lists summary and cheatsheet
Lists summary
The table below provides a summary of everything covered above:
List indexing
Lists | |
---|---|
Create a list | class_marks = [99, 68, 72, 50, 72] |
Access the first item in a list | class_marks[0] Output: 99 |
Access the second item in a list | class_marks[1] Output: 68 |
Access the last item in a list | class_marks[-1] Output: 72 |
Access a slice from the middle of a list | class_marks[1:3] Output: [68, 72] |
Access a slice from the start of a list | class_marks[:3] Output: [99, 68, 72] |
Access a slice from the end of a list | class_marks[-2:] Output: [50, 72] |
Add a single item to a list | class_marks.append(83) |
Add multiple items to a list | class_marks.extend([49, 55]) |
Insert an item at a specified index point | class_marks.insert([1, 38]) (inserts at index point 1) |
Remove an item from a list | class_marks.remove([68]) |
Pop an item from a list | class_marks.pop([68]) |
Delete the item at a specified index point | del class_marks[0] (deletes the first mark in the list) |
Sort list items in ascending order | class_marks.sort() |
Get the sum of all list items | sum(class_marks) |
Get the length of the list (# items) | len(class_marks) |
Get the lowest item | min(class_marks) |
Get the highest item | max(class_marks) |
Lists cheatsheet
Dictionaries
While a simple list may be sufficient for storing values and carrying out operations like finding the average, what if we wanted to have a record not just of the class marks, but of which students got which marks? That's where dictionaries come in. Dictionaries are identified with curly brackets as opposed to square brackets and contain a series of key/value pairs.
Note that the methods we used on our lists - indexing to retrieve values, insert()
, extend()
, append()
etc. - do not work on dictionaries. We need to learn a new set of methods, as shown below.
Creating and displaying dictionaries
-
Use the following code to create an empty dictionary:
student_marks = {}
Alternatively, skip straight to the next step and create the dictionary with its key/value pairs already defined.
-
Use the following code to create a dictionary of student marks. Note that for each item in the list, the key (in our case, the student's name) comes first. Since names are strings, we put them in quotation marks. After the key comes a colon, followed by the value (in our case, a mark which is an integer). Each key/value pair is separated by a comma:
student_marks = {"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72}
-
Ask Python to display the dictionary with the following code:
student_marks
Output:
{"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72}
Accessing keys and values within the dictionary
There are a number of different ways to access the keys and values within the dictionary.
-
Use the following code to find the value associated with a given key. In this case, we want to know Sara's mark:
student_marks.get("Sara")
Output:
99
-
Use the following code to get a view object showing a list of all the keys in the dictionary, in our case the list of student names:
student_marks.keys()
Output:
dict_keys(['Sara', 'Aneesa', 'Emmanuel', 'Tom', 'Candice'])
-
Use the following code to get a view object showing a list of all the values in the dictionary, in our case the list of student marks:
student_marks.values()
Output:
dict_values([99, 68, 72, 50, 72])
Adding items to a dictionary
-
Use the following code to add a new item to the dictionary, then display the dictionary. In our case we imagine we have a new student called Paxton:
student_marks["Paxton"] = 76 student_marks
Output:
{'Sara': 99, 'Aneesa': 68, 'Emmanuel': 72, 'Tom': 50, 'Candice': 72, 'Paxton': 76}
The
update()
method lets us add one or many key/value pairs to the dictionary: -
Use
update()
to add two new students and their marks to the dictionary, then display the dictionary:student_marks.update({"Devi": 80, "Fabiola": 55}) student_marks
Output:
{'Sara': 99, 'Aneesa': 68, 'Emmanuel': 72, 'Tom': 50, 'Candice': 72, 'Paxton': 76, 'Devi': 80, 'Fabiola': 55}
Removing items from a dictionary
Some of these methods and keywords will be familiar from the list section of the tutorial.
-
Use the
pop()
method to remove a key/value pair from the dictionary, specified by the key. Then display the dictionary again to check it has gone:student_marks.pop("Emmanuel") student_marks
Output:
{'Sara': 99, 'Aneesa': 68, 'Tom': 50, 'Candice': 72, 'Paxton': 76, 'Devi': 80, 'Fabiola': 55}
As with lists, we can use
pop()
to create a new variable. -
Use the
pop()
method to remove Aneesa's mark and put it in a new variable:aneesa_mark = student_marks.pop("Aneesa") aneesa_mark
Output:
68
Also, similar to lists, we can use the
del
keyword to delete an item, specified by its key: -
Use the
del
keyword to delete Sara's mark and then display the dictionary:del student_marks["Sara"] student_marks
Output:
{'Tom': 50, 'Candice': 72, 'Paxton': 76, 'Devi': 80, 'Fabiola': 55}
Finally, we can use the
clear()
method to wipe everything from the dictionary. -
Use
clear()
to clear the dictionary of all its key/value pairs, then display the dictionary:student_marks.clear() student_marks
Output:
{}
Useful dictionary operations
It is generally not as simple to carry out operations on dictionaries as on lists:
- Dictionaries do not, by definition, have any inherent order, so the
sort()
method does not work on them. - You cannot use
max()
,min()
,sum()
etc. to quickly see the maximum, minimum, and sum of values in a dictionary.
A lot of the cool stuff you can do with dictionaries involves using loops, which will be the subject of our next tutorial. But in the interim, here are some things you can do with dictionaries, without using loops:
-
Recreate the
student_marks
variable as it originally was, to give us a base for the rest of this section:student_marks = {"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72}
-
Use
len()
to find out the length of the dictionary (how many key/value pairs it has):len(student_marks)
Output:
5
We saw previously that we can use
values()
to get a view object showing a list of all the values in the dictionary. However, this does not give us an actual list variable, but just a view, so we cannot carry out list operations on it. There's a way to get around this though. We can use thelist()
function, which creates a list object: -
Create a new variable, using
list()
and give itstudent_marks.values()
as an argument. Then display the new variable:marks_only = list(student_marks.values()) marks_only
[99, 68, 72, 50, 72]
Now you have the list of marks, you can use all the list operations we previously saw on it.
Dictionaries summary and cheatsheet
Dictionaries summary
The table below provides a summary of everything covered above:
Lists | |
---|---|
Create a dictionary | student_marks = {"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72} |
Get a value from its key | student_marks.get("Aneesa") Output: 68 |
View all keys in the dictionary | student_marks.keys() Output dict_keys(['Sara', 'Aneesa', 'Emmanuel', 'Tom', 'Candice']) |
Get a list of all values in the dictionary | list(student_marks.values()) |
View all values in the dictionary | student_marks.values() Output: dict_values([99, 68, 72, 50, 72] ) |
Add a single key/value pair to the dictionary | student_marks["Paxton"] = 76 |
Add multiple key/value pairs to the dictionary | student_marks.update({"Devi": 80, "Fabiola": 55}) |
Remove a key/value pair from the dictionary and return (pop) its value | student_marks.pop("Sara") |
Delete a key/value pair from the dictionary | del student_marks['Aneesa'] |
Clear the whole dictionary (delete all key/value pairs) | student_marks.clear() |
Get the length of the dictionary | len(student_marks) |
Dictionaries cheatsheet
Visit our Help Center and find the answers to your most frequent questions.
Visit Help Center