Lists#

Todo

  • Introduire la notion de valeur composite

  • Expliciter que l’ordre et les répétitions sont importantes

  • Améliorer la définition de structure de données

  • Remplacer chaque exercice d’application immédiate par un exercice Jupylates randomisé

A list is a data structure that contains a series of values.

Definition: Data structure

structures de données (data structure) are specific

ways of organizing and storing data so that it can be accessed

and worked with effectively. Data structures define the relationship

between data and the operations that can be performed on it.

Source: https://moncoachdata.com/blog/devenir-python-ninja-structures-de-donnees/

A list is a value that brings together several simpler values into a single structure: this is called a valeur composite.

Python allows the construction of lists containing values of different types (for

example, integer and string). Run the following cells that contain

examples of lists:

animaux = ["girafe", "tigre", "singe", "souris"]
tailles = [5, 2.5, 1.75, 0.15]
mixte = ["girafe", 5, "souris", 0.15]
animaux
['girafe', 'tigre', 'singe', 'souris']
tailles
[5, 2.5, 1.75, 0.15]
mixte
['girafe', 5, 'souris', 0.15]

Manipulating List Elements#

Indices#

Since the order of elements in a list is fixed, a given element can be accessed from its indice (array index), that is, its position in the list. The following example

liste  : ["girafe", "tigre", "singe", "souris"]
indice :     0         1        2        3

Attention

The indices of a list of \(n\) elements start at \(0\) and therefore end at \(n-1\).

One can then access the element of index i of a list l with the notation l[i].

Here, for example, are the first and third elements of our list of animals:

animaux[0]
'girafe'
animaux[2]
'singe'

The elements of a list are also indexed by negative numbers according to the following model:

following:

liste          : ["A", "B", "C", "D", "E", "F"]
indice positif :   0    1    2    3    4    5
indice négatif :  -6   -5   -4   -3   -2   -1

Negative indices count from the end. They thus allow

access to the last element of a list using the index -1 without

knowing the length of this list.

It is also possible to assign a value to l[i]; this will have the effect of changing

the value of l at index i:

tailles = [5, 2.5, 1.75, 0.15]
tailles
[5, 2.5, 1.75, 0.15]
tailles[2] = 1.5
tailles
[5, 2.5, 1.5, 0.15]

Exercises

Indication: execute the two cells below to display the

exercises.

from jupylates import Exercise
Exercise("listes/couleurs1.md", dir="../exercices")
Exercise("listes/couleurs2.md", dir="../exercices")

Slices#

It is possible to extract consecutive elements from a list by using an index of

the form m:n+1 to retrieve all the elements from the m-th included to the n-th excluded. We

then say that we are extracting a tranche (slice) from the list. Here are some

examples:

animaux = ["girafe", "tigre", "singe", "souris"]
animaux[0:2]
['girafe', 'tigre']
animaux[0:3]
['girafe', 'tigre', 'singe']
animaux[0:]
['girafe', 'tigre', 'singe', 'souris']
animaux[:]
['girafe', 'tigre', 'singe', 'souris']
animaux[1:]
['tigre', 'singe', 'souris']
animaux[1:-1]
['tigre', 'singe']

When no index is indicated to the left or right of the : symbol, Python extracts by default all the elements from the beginning, or all the elements to the end respectively.

: We can also specify the step by adding an additional symbol and specifying this step by an integer:

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
x[::1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
x[::2]
[0, 2, 4, 6, 8, 10, 12]
x[::3]
[0, 3, 6, 9, 12]
x[1:10:3]
[1, 4, 7]

Source: https://docs.python.org/fr/3/glossary.html

Todo

Un poil redondant avec ci-dessus

Definition: Slices

A tranche (slice) in Python is an object containing a portion of a sequence.

A slice is created using the [] notation with : between the numbers

when several are provided; it works on the model liste[début:fin:pas]. We

find the same principle as for the range function which could take up to three

parameters: range(début, fin, pas).

Note

Everything we have seen on lists generalizes to strings.

Todo

Donner un exemple.

Exercises

Indication: execute the two cells below to display the

exercises.

from jupylates import Exercise
Exercise("listes/tranches1.md", dir="../exercices")
Exercise("listes/tranches2.md", dir="../exercices")

Building lists with range and list#

We saw the function range() in the

sheet on loops.

When used in combination with the list() function, we get a list

of integers:

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Exercises

Indication: execute the two cells below to display the

exercises.

from jupylates import Exercise
Exercise("listes/range1.md", dir="../exercices")
Exercise("listes/range2.md", dir="../exercices")

Operations on multiple lists#

Lists of lists#

Lists are objects like any other, so I have the right to manipulate them. I can

make a list of whatever I want, so I can make a list of lists. It is possible

to construct lists of lists. For example:

enclos1 = ["girafe", 4]
enclos2 = ["tigre", 2]
enclos3 = ["singe", 5]
zoo = [enclos1, enclos2, enclos3]
zoo
[['girafe', 4], ['tigre', 2], ['singe', 5]]

In this example, each sublist contains an animal category and the number

of animals for each category.

To access an element of the list, we use the usual indexing:

zoo[1]
['tigre', 2]

To access an element of the sub-list, we use a double index:

zoo[1][0]
'tigre'
zoo[1][1]
2

Concatenation and multiplication#

Lists support the + concatenation operator, as well as the * operator for

duplication. There is a function liste1.extend(liste2) which allows doing the same

concatenation operation as + (liste2 is concatenated to liste1). Note:

the operation liste1 + liste2 returns the concatenation of the two lists, while

liste1.extend(liste2) puts the concatenation of the two lists into liste1.

Execute the following cells:

ani1 = ["girafe", "tigre"]
ani2 = ["singe", "souris"]
ani = ani1 + ani2
ani
['girafe', 'tigre', 'singe', 'souris']
ani1.extend(ani2)
ani1
['girafe', 'tigre', 'singe', 'souris']
ani1 * 3
['girafe',
 'tigre',
 'singe',
 'souris',
 'girafe',
 'tigre',
 'singe',
 'souris',
 'girafe',
 'tigre',
 'singe',
 'souris']
a = [] #Création d'une liste vide
a = a + [15] #Ajout de l'élément 15
a
[15]
a = a + [-5] #Ajout de l'élément -5
a
[15, -5]

Operations on a single list#

Functions on the elements of a list#

Here are some other list functions that you need to know:

  • liste.append(a): add a single element a to the end of a list. Reminder:liste1.extend(liste2) allows you to add an entire list liste2 after liste1.

  • liste.remove(a): searches for the element a in the list and deletes the first occurrence found.

  • liste.insert(i, a): to insert a new element a at a specific position i. For example, liste.insert(1, 12) will insert the integer 12 at index 1, moving the old element 1 to index 2 and so on;

  • liste.index(a): allows you to find the index of the first occurrence of the element a to search for in our list.

  • del liste[i]: allows you to delete the element at index i.

Here are some examples:

liste = [] # Déclaration d'une liste vide
liste.append(7) # -> [7]
liste.append(5) # -> [7, 5]
liste.insert(1,12) # [7, 12, 5]
liste[0] = 4 # -> [4, 12, 5]
liste.remove(12) # [4, 5]
liste.index(5) # affiche 1
liste.extend([1, 2, 3]) # [4, 5, 1, 2, 3]
del liste[3] # [4, 5, 1, 3]

The size of a list#

The len() function allows you to know the length of a list, that is to say the number

of elements that the list contains.

animaux = ["girafe", "tigre", "singe", "souris"]
len(animaux)
4
len([1, 2, 3, 4, 5, 6, 7, 8])
8

Minimum, maximum, and sum of a list#

The functions min(), max() and sum() return the minimum, the maximum

, and the sum of a list passed as an argument, respectively.

liste = list(range(10))
liste
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
sum(liste)
45
min(liste)
0
max(liste)
9

Overview#

Operation

Definition

Operation on a single list

liste.append(a)

Adds the element a to the end of liste

liste.remove(a)

Removes the first occurrence of a in liste.

liste.insert(i, a)

Inserts a new element a at position i.

liste.index(a)

Returns the index of the first occurrence of a in liste.

del liste[i]

Removes the element at index i.

len(liste)

Returns the length of liste.

min(liste)

Returns the smallest element of liste.

max(liste)

Returns the largest element of liste.

Operation on multiple lists

liste1 + liste2

Returns the concatenation of liste1 and liste2.

liste * n

Returns the concatenation of n copies of liste.

liste1.extend(liste2)

Adds the elements of liste2 to the end of liste1.

Todo

  • Filtrer les exercices faisables à ce stade: compréhension; 2D?

  • Exo operations_plsrs_listes.md: affichage incorrect du code

Before moving on, we offer some self-correcting training and review exercises.

**You can ignore the listes_comprehension and

operations_plusieurs_listes exercises for the time being.**

import glob, os
from jupylates import Exerciser
os.chdir("../exercices")
exercises = glob.glob('listes/*.md')
Exerciser(exercises)