7  Les séquences

Une séquence est une collection d’éléments ordonnés.

Parmi les types de bases, les séquences sont :

7.1 Création

7.1.1 Créer une chaine de caractères

my_string = ''
my_string = ""
my_string = str()

king = "Arthur"

7.1.2 Créer une liste

my_list = []
my_list = list()

camelot = ['Arthur', 'Merlin', 'Lancelot', 
           'Robin', 'Bohort', 'Perceval', 'Karradoc']

7.1.3 Créer un n-uplet (tuple)

my_tuple = tuple() # tuple vide

wizards = 'Merlin',
tavern = 'Perceval', 'Karradoc',

7.2 Taille

Avec la fonction len(seq)

>>> len(king)
6
>>> len(camelot)
7
>>> len(wizards)
1

7.3 Accès à un élément

Par indexation (subscript)

>>> king[2]
't'
>>> camelot[1]
'Merlin'
>>> tavern[0]
'Perceval'
>>> king[-1]
'r'
>>> camelot[-2]
'Perceval'
>>> tavern[-1]
'Karradoc'

7.4 Test élément dans séquence

Avec le mot-clef in

>>> 't' in king
True
>>> 'Mordred' in camelot
False
>>> 'Tavernier' in tavern
False

7.5 Unpacking

Fonctionne avec toute séquence

>>> quest = ['Rabbit of Caerbannog', 'cave', 
...          'Location of the Holly Grail']
>>> opponent_name, location, reward = quest
>>> opponent_name
'Rabbit of Caerbannog'
>>> location
'cave'
>>> reward
'Location of the Holly Grail'

7.6 Slicing

Structure : `seq[start:stop:step]

>>> king[2:5]
'thu'
>>> camelot[2:6]
['Lancelot', 'Robin', 'Bohort', 'Perceval']
>>> camelot[:2]
['Arthur', 'Merlin']
>>> camelot[3:]
['Robin', 'Bohort', 'Perceval', 'Karradoc']
>>> camelot[-2:]
['Perceval', 'Karradoc']