NavigationContentFooter
Jump toSuggest an edit

Getting started with Python lists and dictionaries

Reviewed on 08 October 2024Published on 23 March 2023
  • python
  • loops
Requirements

If you’re coming to this tutorial as a complete Python beginner, make sure you’re familiar with the Python concepts covered in our Python for complete beginners tutorial first. You might also be interested in the next tutorial in the series: Getting started with Python for-loops.

Tip

If you’re not a beginner and just looking for a quick review/cheatsheet, skip to:

  • Python Lists: summary/cheatsheet
  • Python Dictionaries: summary/cheatsheet

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.

  1. 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.

  2. Use the following code to create a list of class marks:

    class_marks = [99, 68, 72, 50, 72]
  3. Ask Python to display the list of marks with the following code:

    class_marks
Tip

In this example, we’ve created a list of integers (whole numbers), but you can store any type of variable in a list. Look at the following examples:

  • student_names = ["Sara", "Aneesa", "Emmanuel", "Tom", "Candice"] creates a list of strings
  • random_list = [54.5, "hello", 64, True, 1, "NO"] creates a list with a mixture of variable types
  • list_of_lists = [[62, 92, 54.5], ["Jones", "Smith", "Ali"], [True, 1, "maybe"]] creates a list of lists.

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.

  1. 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.

  2. Use the following code to change the second mark in the list:

    class_marks[1] = 67
  3. 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:

  4. 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.

  1. 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.

  2. 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.

  3. 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]
Tip

What happens if you use slicing with the reverse index (the minus number index positions)? Try it out and see.

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.

  1. Use the append() method to add a new mark of 83 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.

  2. Use the extend() method to add two new marks of 49 and 55 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]
    Tip

    Try out the following to see how to use extend() with an existing list:

    group1_marks = [62, 51]
    group2_marks = [48, 80]
    group1_marks.extend(group2_marks)

    Finally, the insert() method lets us insert a new item to a list in a specific index point.

  3. Use the insert() method to add a mark of 30 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]

  1. 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]
    Tip

    If you use the remove() method with an item that has more than one occurrence in the list (e.g. for the mark 72 in our case) it will remove the first occurrence of the item only.

    Next, we have the pop() method, which removes the item at the specified index position:

  2. 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:

  3. 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)
  4. Use the following code to check the current values of class_marks and single_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.

  5. 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]
  6. 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.

  7. 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.

Tip

Note that the syntax for appending, removing, extending, etc. is list_name.method_name(), whereas the syntax for deleting is del list_name. This is because append, remove, extend, etc. are all methods, whereas del is a keyword. Methods and keywords have different syntax, even if they both carry out operations on a given variable or item.

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.

  1. 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]
  2. 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]
    Note

    By default, sort() sorts the list in ascending order. Use class.marks.sort(reverse=True) to sort into descending order.

  3. Use the sum() method to get the sum of all marks in the list:

    sum(class_marks)

    Output:

    361
  4. 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
  5. Use the sum() and len() methods together to calculate the average mark, and then display it:

    average_mark = sum(class_marks) / len(class_marks)
    average_mark

    Output:

    72.2
Tip

Try using the methods min(), max(), and set() on the class_marks list, to get the lowest mark, highest mark, and list of unique marks with any duplicates eliminated.

Lists summary and cheatsheet

Lists summary

The table below provides a summary of everything covered above:

List indexing

Lists
Create a listclass_marks = [99, 68, 72, 50, 72]
Access the first item in a listclass_marks[0] Output: 99
Access the second item in a listclass_marks[1] Output: 68
Access the last item in a listclass_marks[-1] Output: 72
Access a slice from the middle of a listclass_marks[1:3] Output: [68, 72]
Access a slice from the start of a listclass_marks[:3] Output: [99, 68, 72]
Access a slice from the end of a listclass_marks[-2:] Output: [50, 72]
Add a single item to a listclass_marks.append(83)
Add multiple items to a listclass_marks.extend([49, 55])
Insert an item at a specified index pointclass_marks.insert([1, 38]) (inserts at index point 1)
Remove an item from a listclass_marks.remove([68])
Pop an item from a listclass_marks.pop([68])
Delete the item at a specified index pointdel class_marks[0] (deletes the first mark in the list)
Sort list items in ascending orderclass_marks.sort()
Get the sum of all list itemssum(class_marks)
Get the length of the list (# items)len(class_marks)
Get the lowest itemmin(class_marks)
Get the highest itemmax(class_marks)

Lists cheatsheet

Tip

This content is also available as a printable PDF file. Download the Python lists cheatsheet - Printable (PDF, 2.9MB).

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

  1. 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.

  2. 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}
  3. Ask Python to display the dictionary with the following code:

    student_marks

    Output:

    {"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72}
    Tip

    In this example we’ve created a dictionary where the keys are strings and the values are integers. Values can be any variable type you want, and keys can be any immutable variable type. This means you can use integers, floats, strings, and booleans as keys, but you cannot use lists or dictionaries as keys.

    All the following are valid dictionary creation statements. The last one is a dictionary of dictionaries.

    • random_dictionary = {9: "hello", "seven": true, 10.5: ["one", 19, false]}
    • sara_stats = {"Name": "Sara", "Family name": "Snook", "Age": 35, "Alive": True}
    • my_pets = {"Toby": {"Animal: "Dog", Breed": "Labrador", "Age": 2}, "Goldie": {"Animal: "Fish, "Breed": "Goldfish", "Age:": 1}}

    Every key in a dictionary must be unique. It cannot be repeated. However, values do not have to be unique within the dictionary.

Accessing keys and values within the dictionary

There are a number of different ways to access the keys and values within the dictionary.

  1. 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
    Tip

    It is also possible to use the syntax student_marks["Sara"] for the same purpose, but this usage is not considered optimal by Python. This is because if you look up a key that does not exist in the dictionary, e.g. student_marks["Greg"], Python returns an error. When using the get() syntax to look up a key that does not exist in the dictionary, Python simply returns a None response.


    You can add an extra argument to the get() method, to tell Python what to return if the key does not exist. For example student_marks["Greg", "Not in dictionary"] returns "Not in dictionary"/

  2. 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'])
  3. 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

  1. 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:

  2. 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.

  1. 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.

  2. 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:

  3. 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.

  4. 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:

  1. 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}
  2. 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 the list() function, which creates a list object:

  3. Create a new variable, using list() and give it student_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 dictionarystudent_marks = {"Sara": 99, "Aneesa": 68, "Emmanuel": 72, "Tom": 50, "Candice": 72}
Get a value from its keystudent_marks.get("Aneesa") Output: 68
View all keys in the dictionarystudent_marks.keys() Output dict_keys(['Sara', 'Aneesa', 'Emmanuel', 'Tom', 'Candice'])
Get a list of all values in the dictionarylist(student_marks.values())
View all values in the dictionarystudent_marks.values() Output: dict_values([99, 68, 72, 50, 72])
Add a single key/value pair to the dictionarystudent_marks["Paxton"] = 76
Add multiple key/value pairs to the dictionarystudent_marks.update({"Devi": 80, "Fabiola": 55})
Remove a key/value pair from the dictionary and return (pop) its valuestudent_marks.pop("Sara")
Delete a key/value pair from the dictionarydel student_marks['Aneesa']
Clear the whole dictionary (delete all key/value pairs)student_marks.clear()
Get the length of the dictionarylen(student_marks)

Dictionaries cheatsheet

Tip

This content is also available as a printable PDF file. Download the Python dicts cheatsheet - Printable (PDF, 2.87MB)

API DocsScaleway consoleDedibox consoleScaleway LearningScaleway.comPricingBlogCareers
© 2023-2024 – Scaleway