Data structures

Lists

List = comma-separated hetereogenous values (items) between square brackets


In [5]:
A = [1, 2, 5, 7, 9]
B = ['Riri', 'Fifi', 'Loulou']
C = ['a', 1, 2, None, True]
  • Lists can be indexed (index starts at 0) and sliced.

In [13]:
print(A[0]); print(A[2]); print(B[:2]); print(B[2:]); print(C[2:4])


1
5
['Riri', 'Fifi']
['Loulou']
[2, None]

Negative indexing and slicing works


In [14]:
print(A[-1]); print(A[:-1]); print(C[2:-1])


9
[1, 2, 5, 7]
[2, None]
  • Concatenation ? Yes !

In [20]:
A + B


Out[20]:
[1, 2, 5, 7, 9, 'Riri', 'Fifi', 'Loulou']
  • Length of a list ?

In [17]:
len(A)


Out[17]:
5
  • Lists of lists ?

In [19]:
[A, B]


Out[19]:
[[1, 2, 5, 7, 9], ['Riri', 'Fifi', 'Loulou']]
  • Assignement ?

In [27]:
A = [1, 2, 3, 4, 5]
A[2:4] = []
print(A)
A[1:2] = [10, 20]
print(A)


[1, 2, 5]
[1, 10, 20, 5]
  • Adding an element ?

In [26]:
B.append('Picsou')
print(B)


['Riri', 'Fifi', 'Loulou', 'Picsou', 'Picsou']

Lists are mutable !


In [ ]: