Python Programmation language
Chapitre 4
Object collections in Python
TUPLES, LISTS, DICTIONARIES
Static read-only array of heterogeneous objects
TUPLES
Creation of tuples and data access
#définition d'un tuple The ( ) are important to indicate that it is a
t1 = (2,6,8,10,15,26) tuple, « , » separates the items.
print(t1)
#taille du tuple (2,6,8,10,15,26)
print(len(t1)) 6 items
#accès indicé
Firstitem, indices go from 0 to len(t1)-1
a = t1[0]
print(a) Note: a is not a tuple
#modification ?
t1[2] = 3 ERROR
#plage d'indices
b = t1[2:5] Warning: we recover from n°2 (included) ton°5
print(b) (not-included) i.e.. the indices 2, 3, 4
#autre plage Result : b is a tuple with (8,10,15)
c = t1[:4]
print(c) The 4 first items i.e. the indices 0, 1, 2, 3 : we obtain the tuple
#indiçage négatif (2, 6, 8, 10).
d = t1[-1]
print(d) Le 1er last from the end :26
#indiçage négatif
e = t1[-3:]
print(e) The 3 last items : (10,15,26)
#concatenation
t2 = (7, 9,31) (2,6,8,10,15,26,7,9,31)
t3 = t1 + t2
print(t3)
(7,9,31,7,9,31)
#replication
t4 = 2 * t2
print(t4) it poses no problem
#tuples heterogeneous objects
v1 = (3,6,"toto",True,34.1)
print(v1)
Kind of 2-dimensional array
#tuple of tuples
x = ((2,3,5),(6,7,9),(1,8))
print(x)
x[0] → (2,3,5) Organisationf of
# indexed access x[1] → (6,7,9) the structure
print(x[2][1]) → 8 x[2] → (1,8)
#access to size
print(len(x)) → 3 3 items on the 1ère dimension
print(len(x[2])) → 2 2 items in the tuple referenced by x[2]
Review of tuples
Type ‘tuple’ cf. call type() function
Collection of objects of heterogeneous types
Size and content fixed when writing the program
Cannot modify: non-mutable object
Tuple type variable is actually a reference (pointer to pointer)
Benefits from the crumb collection mechanism
Indexed access, range of indices possible, negative indices also possible
Complex structures with tuple of tuples, and even more – see later
Exercice
1. Crée un tuple couleurs = ('rouge', 'vert', 'bleu’).
2. Affiche le deuxième élément.
3. Essaie de modifier un élément du tuple. Que se passe-t-il ?
Dynamic read-write array of heterogeneous objects
LISTS
List – type list
List ≈ tuple of dynamic and modifiable size
#définition d'une liste The[ ] are important indicates that it is a
list « , » separates items.
L1 = [2,6,8,10,15,26]
print(L1) [2,6,8,10,15,26]
#taille de la tuple [2,6,3,10,15,26]
= 6 print(len(L1))
The other mechanisms associated
#accès indicé
with tuples can be transposed to
= 2 a = L1[0]
lists:
print(a) index ranges
negative indications
#modification ! Possible heterogeneous objects
! list of lists (2D or more arrays)
L1[2] = 3 concatenation, replication
print(L1)
Modification of size and content
#autre liste A list is an object (class instance) to which methods
L2 = [32,69,28,69] are associated allowing it to be manipulated.
#ajout
[Link](21) [32,69,28,69,21]
print(L2)
#insertion à l'indice 1
[32,53,69,28,69,21]
[Link](1,53)
print(L2)
#suppression elt n°3
[32,53,69,69,21] 28 has disappeared
del L2[3]
from L2
print(L2)
#accès + suppression elt n°1
a = [Link](1) [32,69,69,21] 53 has disappeared
print(a) → renvoie 53 from L2
#inversion
[Link]()
[21,69,69,32]
print(L2) Note : [Link]()
#étendre Allow you to empty list
[Link]([34,55]) [21,69,69,32,34,55]
print(L2)
« List Comprehensions »
Objective : a simple (and concise) mechanism to generate a list from another list
Example 1 : Square all numbers
source = [1,5,8,12,7]
resultat = [] resultat = [v**2 for v insource]
for v in source: print(resultat)
[Link](v**2)
print(resultat)
Exemple 2 : conditionnal task
source = [1,5,8,12,7]
resultat = []
for v in source: resultat = [v**2 for v in source if (v %2== 0)]
if (v % 2 == 0): print(resultat)
[Link](v**2)
print(resultat)
Content Processing
L2 = [21,69,69,32,34,55]
#search for item
trouve = 32 in L2 Return True since the value
print(trouve) 32 is in the list
#index
Return 4 since the value 34 appears at
id = [Link](34)
index n°4 (index of the 1st found)
print(id)
#counting Return 2 since the value 69 appears
nb = [Link](69) twice in the list
print(nb)
#remove by value Remove the value 69 from the list,
the first that the method will find
[Link](69)
print(L2) [21,69,32,34,55]
This mechanism works with any type of object as long as a
comparison is possible (e.g. string, etc.)
A variable of list type is a reference
#L3
L3 = [61,92,17]
print(L3)
#affectation ? In reality , Is the reference that is copied
L4 = L3
print(L4) L3and L4 « point » to the same place
#modification d'une valeur
L4[1] = 55
#répercussions
print(L4) → [61,55,17]
#mais aussi sur L3
print(L3) → [61,55,17] ???
#L3
L3 = [61,92,17]
#copie des valeurs
L4referen ce a new memory area,
L4 = [Link]()
print(L4) And the Data in L3 y are copied.
L4[1] = 55
print(L4) → [61,55,17]
print(L3) → [61,92,17] !!! L3 is not impacted.
An example : sum of valu es ent ere d by t he u ser
An example (again): direct loop on the elements of the list
Allow to define and create
An initially empty list.
A list is directly
“iterable”, there is no need to
use an index
Exercice
1. Crée une liste nombres = [2,4,6,8,10] et affiche le troisième élément.
2. Ajoute le nombre 12 à la liste et supprime 4.
[Link] la liste et affiche chaque élément au carré.
[Link] le plus grand et le plus petit nombre dans la liste.
[Link] 5 nombres à l’utilisateur et stocke-les dans une liste, puis affiche la
moyenne.
6.Écris un programme qui inverse une liste.
7.Écris un programme qui fusionne deux listes [1,2,3] et [4,5,6].
8.Écris un programme qui compte combien de fois un élément apparaît dans une
liste.
A special case of list
String
A string is a particular list with associated methods
#définir une chaîne
s1 = "bonjour le monde"
Quotes to delimit a string
print(s1)
#longueur
long = len(s1) Mechanism identical to
print(long) tuples and lists
#accès indicé
s2 = s1[:7]
print(s2) ERROR. A string cannot be edited. It is necessary to put
#non modifiable
#s1[0] = "B" the result of a manipulation in another chain.
#méthodes associées
S = [Link]()
print(S)
#recherche d'une sous-chaîne
id = [Link]("JO") Specific methods allow you to
print(id) 3 (1ère occurrence si plusieurs) manipulate strings. See
#nb d'occurences [Link]
nb = [Link]("ON") [Link]#text-sequence-type-str
print(nb) 2
#remplacement de « O » par « A »
SA = [Link]("O","A")
print(SA)
Explicit transformation into a list (for processing)
A string can be transformed into a list to carry out sophisticated
processing. The tool is very flexible.
[‘B’,’O’,’N’,’J’,’O’,’U’,’R’,’ ‘,’L’,’E’,’ ‘,’M’,’O’,’N’,’D’,’E’]
#transf. en liste All operations on the lists are possible thereafter.
liste = list(S)
print(liste)
[‘BONJOUR’,’LE,’MONDE’]
Space is used as a separator here, but it
#découpage par séparateur
can be any other character, including a
decoupe = [Link](" ")
special character (e.g. \t for tab)
print(decoupe)
#former une chaîne à
#partir d’une liste
SB = "-".join(decoupe) "BONJOUR-LE-MONDE"
print(SB) The words in the list have been merged with
the "-" separator. Any separator is possible,
including the empty string.
An example
List with key access
DICTIONARIES
Dictionnary - The type dict Dictionnaire : unordred
#définition d'un dictionnaire
d1 = {'Pierre':17, 'Paul':15,'Jacques':16}
(unindexed) collection of
print(d1) objects (simple or
#ou complex) based on the
Noter le rôle de { }, de « :»
print([Link]())
et « ,» associative mechanism
#nombre d'élements « key – value ».
print(len(d1)) → 3 items
#liste des clés
[‘Paul’, ‘Jacques’, ‘Pierre’]
print([Link]())
#liste des valeurs [15, 16, 17]
print([Link]())
#accès à une valeur par clé Notes :
print(d1['Paul']) → 15 1) [Link]()
#ou empty the dictionnary
print([Link]('Paul')) → 15
(2) d1 is a reference,
#si clé n'existe pas [Link]() allow to
print(d1['Pipa']) → ERROR copy the content.
Dictionary – Modifications, additions and deletions
#modification
{'Pierre':17, 'Paul':15,'Jacques':16} → {'Pierre':17, 'Paul':15,'Jacques':18}
d1['Jacques'] = 18
print(d1) Adding by definition a new “key – value». N.B.:
If ‘Henri’ already exists, its old value will be
#ajouter un élément overwritten.
d1['Henri'] = 22
{'Pierre':17, 'Paul':15,'Jacques':18, ‘Henri’:22}
print(d1)
#ajout d'un bloc d’éléments
[Link]({'Monica':36,'Bill':49})
print(d1)
{'Pierre':17, 'Paul':15,'Jacques':18, ‘Henri’:22, ‘Monica’:36, ‘Bill’ : 49}
#détecter présence clé
test = 'Pierre' in d1
print(test) → True
#suppression par clé
del d1['Monica']
print(d1) {'Pierre':17, 'Paul':15,'Jacques':18, ‘Henri’:22, ‘Bill’ : 49}
Further with the keys
Keys are not necessarily strings. The tool is very flexible
but, be careful, so much freedom can also be
detrimental. You have to be very rigorous.
#autre type de clé
d2 = {('Pierre',56):['Directeur',1253,True],('Paul',55):['Employé',100,False]}
print([Link]())
print([Link]())
In thisexample :
• Key is a tuple;
• value is a list.
Example
Example :
Kate 15.0
Pipa 23.5
William 10.7
49.2
Exercice
1. Crée un dictionnaire etudiant = {'nom': 'Sara', 'age': 21, 'note': 16}
1. Affiche la valeur associée à la clé 'nom’.
2. Ajoute une nouvelle clé 'ville' avec une valeur.
3. Modifie la note de l’étudiant.
Parcourt le dictionnaire et affiche clé et valeur.
1. Crée une liste de dictionnaires pour représenter une classe de 3 étudiants.
2. Écris un programme qui demande un nom et cherche s’il existe dans le
dictionnaire.
3. Crée un dictionnaire qui compte le nombre de lettres dans un mot saisi par
l’utilisateur.