• 6 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 21/01/2021

Store multiple elements with lists and dictionaries

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

Imagine you are the communications manager of a fashionable theater. One of your main responsibilities is to manage the front row, which means making sure that the artists' relatives and friends, as well as other VIPs, get the best view.

If all you had to do was handle two invitations for the main artist, you could use just two variables holding the guest's name. The Python code would look like this:

# Declare a variable for each guest in the front

Then, when the performer gives you the information, you would assign a name to each variable. For instance, you would have:

# Assign the guest namesfront
RowGuest1="Mary Poppins"
frontRowGuest2="Jane Banks"

Now, if your front row is composed of 10 seats, wouldn't it be easier if you could use just one variable that would contain all that information?

Lucky you! Python offers a data structure capable of holding a fixed number of values. This structure is called a list. Let's see when and how to use one.

Use a list to store several elements

list is a numerically ordered sequence of elements. This means that each element is associated with a number. That number is called an index which starts with 0 (not 1!). So the first element is associated with an index 0, the second with 1, etc.

Declaring a list uses the same syntax as for any variable. You provide:

  1. The variable name that clearly expresses the intent of the array.

  2. The values stored in your list

For instance, you could store your fruits in a list as if it was a basket of fruit:

basketOfFruits = ['orange', 'apple', 'banana', 'strawberry']

Now that your list is created, you can perform two operations on it:

1. Access a value at a given index.
2. Set a new value at a given index.

In both cases, use the name of the variable followed by [, the value of the index, and ].

For instance, if you swap your banana (the 3rd fruit) with a cherry, you can write:

# Assign the value "cherry" to the 3rd fruit in the basket
# That's index 2, since the first index is 0
basketOfFruits[2] = "cherry"

To print the first fruit contained in your basket, write the following statement:

# Print the first fruit in your basket
print(basketOfFruits[0])

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. You can also access a range of items in a list by using the slicing operator (colon).

# print the last element
print(basketOfFruits[-1])
# access elements 2nd to 4th :
print(basketOfFruits[1:3])
# elements beginning to 3rd :
print(basketOfFruits[:2])

We tried a list of strings, but you can also do that with some numerical elements:

numericList = [4, 2, 3, 10.2]

For example, the following list is correct:

strangeList = [4, 10.2, "cherry", ["an other list", 1]]
# try to print the 4th element :
print(strangeList[3])
Try it out for yourself!

What about your theater's front row? Well, you just need to create a list with the number of seats your front row contains. You can either add all your guests at the time of creation or add them individually using the [] syntax.

Practice arrays with the following interactive exercise:

Console de code
Houston... ?
Il semblerait que votre ordinateur ne soit pas connecté à Internet.
Vous n'êtes pas connecté

Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.

Pensez à vous entraîner avant de terminer ce chapitre.

Lists are efficient and great if you manage a fixed number of elements. In practice, you often have to deal with a varying number of elements. Python makes it easy to deal with those cases with a lot of list methods.

Python list methods: add and delete an element

Let's say you wanted to list animals in order of their cuteness, and you start off will a small list of four items: fox, owl, koala, and otter. Now, let's say you want to add a squirrel between the fox and the owl.

adorable squirrel
This one deserves a spot at the top

Lists are mutable, which means they allow you to modify the contents of a collection of elements, including changing the number of elements.

Among other things, lists allows you to:

  • Search for a specific element in the list.

  • Append (add) a new element to the end. 

  • Insert a new element at a specific index.

  • Remove an element at a specific index.

Create a list and add elements

First of all, you can only create an empty list in Python. You have to add elements one by one like this:

myList = []
myList.append(7)
myList.append(5) # => [7,5]
  1. The first statement creates an empty list named myList.

  2. We then added a first element with the mylist.append(7) statement. Python adds it to the list at the 0 index.

  3. Finally, the myList.append(5) adds a 5 integer element to the list at index 1. 

Now, what is .append()? In Python, adding, modifying, or removing elements requires using a method, and you guessed it, .append()is one!   At this point, all you need to know about methods is that they let you do things. 😎

There are some methods implemented by the List class that come in handy:

  • append- to add a new element at the end of an array. Here you need to provide a new element.

  • You can also place a new element in a given position by specifying the index through the  insert method. For instance, myList.insert(1,12) will insert an integer with value 12 at position 1, and move the existing value at position 2, and so on.

  • remove- searches for the given element in the list and removes the first matching element. For example, if you want to delete 5 from your list, you use   myList.remove(5).

  • index- method finds an element in a list and returns its position.

What does all that look like?  Here's the Python syntax for the above:

myList = []
myList.append(7) # -> [7]
myList.append(5) # -> [7, 5]
myList.insert(1,12) # [7, 12, 5]
myList[0] = 4 # -> [4, 12, 5]
myList.remove(12) # [4, 5]
myList.index(5) # print 1

Let's break this down.

  • You can see the same operation from before: adding 7, then 5 to the list. 

  • Then insert 12 at index 1. The existing value at index 1 is moved to index 2.

  • Next, you're asking the List to change the value at index 0.  This will transform the original value, 7, to the new value, 4.

  • Then, with .remove() , you're asking the list to remove the first 12 value found.

  • Finally, you're asking the list to print the index of value 5.

This leaves the final list containing two integers: 4 and 5.

Keep track of the number of elements in your list

The function len() allows you to get the number of elements in a list:

myList = [1, 2, 3]
len(myList) # will print 3

This makes it a lot easier to keep track of the placement of elements in your list.

The len function is extremely used, notably when you need to loop over a list. We'll get to this in the next part.

Try it out for yourself!

Console de code
Houston... ?
Il semblerait que votre ordinateur ne soit pas connecté à Internet.
Vous n'êtes pas connecté

Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.

Pensez à vous entraîner avant de terminer ce chapitre.

Dictionaries

To recap from the video, a dictionary is a list of elements organized by a key.  Just like in a word dictionary, you look for a specific term. In programming, it is called a key. The definition is its value. This is called a KEY <> VALUE association.

For example, if you need to store your friends and their ages, dictionaries are the right collection to use:

Dictionary elements
Dictionary elements

All keys in a dictionary must be unique. 

Declaring dictionaries

Dictionaries and lists are defined the same way except dictionaries are written with curly brackets, and they have keys and values. Here is an example of a dictionary definition:

myDict = {"Jenny": 34, "Livia": 28, "Paul": 31}
print(myDict["Jenny"]) # -> 34

In the last line, we've asked the program to print out the value for our key, Jenny. In this code:

  •  The print() function prints the result of an expression that is provided between its parenthesis

  • The actual expression, myDict["Jenny"], returns the value identified by the key  "Jenny" that is stored in the myDict variable.

When using strings as keys, remember that they are case sensitive. For example, Jenny and jenny are two different keys that will associate with two different elements in a dictionary. For example:

myDict["jenny"] = 21
print(myDict["Jenny"]) # -> 34
print(myDict["jenny"]) # -> 21

To protect against such situations, use variables to specify the keys once, and then reuse them throughout the code:

# define keys as variable
kJenny = "Jenny"
kLivia = "Livia"
kPaul = "Paul";
myDict = {kJenny: 34, kLivia: 28, kPaul: 31}
# access an element
print(myDict[kJenny]) # -> 34

A little more about keys

While the most commonly used type is  String , keys in Python can be of various types, for example, Integer :

myDict[1] = "test"

Like for simple variable types and arrays, the same rules apply to dictionaries: all values and keys can be a different type.

Manipulating dictionary elements

Here are the frequently used operations you can do with dictionaries:

  • Access  the value of an element by its key.

  • Add a new element with a new key and value.

  • Remove an element for a specific key.

Imagine that you have a dictionary of people's names and their jobs, called professions.

  1. You can add a value as seen previously with two arguments: the key and the value.

  2. To access a value, use the key as an argument of the variable containing your dictionary.

Let's check it out:

professions = {} # declare an empty dictionary
professions["Jenny"] = "Business owner"
print(professions["Jenny"]) # -> Business Owner

You can also modify an element by reusing an existing key:

professions = {} # declare an empty dictionary
professions["Jenny"] = "Business owner"
print(professions["Jenny"]) # -> Business Owner
professions["Jenny"] = "Developer"
print(professions["Jenny"]) # -> Developer

 Finally, to remove an element, you can use a pop() method with the key of the element you want to remove:

professions.pop("Jenny")

Counting elements

Dictionaries, like lists, also have the len() function to to get the number of elements in dictionaries:

len(professions) # -> 0 here
Try it out for yourself!

Console de code
Houston... ?
Il semblerait que votre ordinateur ne soit pas connecté à Internet.
Vous n'êtes pas connecté

Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.

Pensez à vous entraîner avant de terminer ce chapitre.

Summary

In this chapter, you've learned the basics of working with containers that store multiple elements of a given data type:

  • Ordered lists (lists) - elements of a list behave like an array. The number of elements can evolve by adding and removing elements.

  • Dictionaries (dict) - elements of a dictionary are organized by key-value pairs and can be accessed using a key.

  • The most common actions performed with collections are:

    • Access an element.

    • Add a new element.

    • Remove an element.

    • Modify an element.

    • Count all elements.

Which collections you choose depend on the task at hand. As you progress with your career, you'll be able to identify the best suitable type to use.

What do you think of this course? Let us know here.

Exemple de certificat de réussite
Exemple de certificat de réussite