Lists and tuples#
Education objectives
listandtupleimmutability and mutability
keyword
inreference and
del
Lists and tuples are the most basic data structures in Python. Let’s see how they can be used and how they differ.
standard type list#
A list is a mutable sequence of (possibly inhomogeneous) elements.
type([0, "a"])
list
# create an empty list
l = []
# fill the list (with the function append)
l.append("2")
# fill the list (with the function extend)
l.extend([6, 3.0])
print(l)
['2', 6, 3.0]
# concatenate lists with the operator +
print(l + ["hello", 3])
['2', 6, 3.0, 'hello', 3]
# get values
print(l[0], l[2], l[-2])
# slicing
print(l[0:2])
2 3.0 6
['2', 6]
standard type tuple#
A tuple is a immutable sequence of (possibly inhomogeneous) elements.
Note
When you need a sequence that won’t be modified, tuple is usually more efficient than list.
t = 0, "a", 1.2
t1 = (5, "hello")
t2 = tuple([1.1, 2])
type(t)
tuple
t[1] # indexing
'a'
t[1:] # slicing
('a', 1.2)
a, b = t1 # tuple assigment
print(b)
hello
Mutable and immutable objects#
We already introduced immutable objects with the types str, int, float, bool. We
can add tuple to the list.
Immutable objects#
The objects of type str, int, float, bool are immutable. They can not be
modified. Of course, a name that points towards an integer can point towards a different
integer.
i = 1
i = i + 2 # (or i += 2)
print(i)
i = 10
print(i)
3
10
Here, the objects 1 and 3 have not been modified.
Mutable objects#
list are the first type of mutable objects that we encounter:
l = [0, 5]
print(l)
l.append("hello")
print(l)
[0, 5]
[0, 5, 'hello']
Here, the object list tagged by the name l has been modified inplace.
Assignment to mutable object#
l = [0, 1, 2, 3, 4, 5]
l1 = l # assignment to a new name l1 (no copy of the object).
# the names l and l1 points towards the same object.
l1.append("a")
print(l1)
print(l)
[0, 1, 2, 3, 4, 5, 'a']
[0, 1, 2, 3, 4, 5, 'a']
Warning
This is different from Matlab, where l1 = l would make a copy.
Shallow copy#
l0 = [0, 1, 2, 3, 4, 5]
l1 = l0.copy() # shallow copy of l0
# can also be written with a slice
# l1 = l0[:]
l1.append("a")
print(l1)
print(l0)
[0, 1, 2, 3, 4, 5, 'a']
[0, 1, 2, 3, 4, 5]
Copies made with list.copy and slicing are shallow.
l0 = []
l_contains_l0 = [l0, 0]
l_contains_l0_bis = l_contains_l0.copy()
l0.append("a")
Can you guess what is the value of l_contains_l0_bis?
l_contains_l0_bis
[['a'], 0]
Note
There is a function deepcopy (importable with from copy import deepcopy) to copy
recursively.
Note for teachers
This can be surprising. Decompose this code with a namespace/memory diagram!
References and del keyword (“delete”)#
del removes a reference (an arrow in a name-space/memory diagram). If an object in not
bound to any names, Python can delete it from its internal memory.
del can remove names (a.k.a. variables):
del l0
Now we cannot access any more the list via the name l0.
l0
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[16], line 1
----> 1 l0
NameError: name 'l0' is not defined
However, the object is still accessible through l_contains_l0 so it cannot be removed
from the memory.
l_contains_l0[0]
['a']
del can delete a reference associated with a container (in our case a list).
del l_contains_l0[0]
l_contains_l0
[0]
However, the list ["a"] is still accessible via l_contains_l0_bis.
l_contains_l0_bis
[['a'], 0]
However, if we del this variable, the list ["a"] is no longer accessible so the
interpreter can remove the object from the memory.
Exercice about strings and lists#
Exercise 9
Suppose we have the string containing header line.
myheader = "wind;temperature;pressure"
Extract the list of items (i.e. “wind”, “temperature”, “pressure”; see
str.split).Add “Snow level” to the list of items (see
list.append)Capitalize all elements of the list (with
str.capitalizeand iterating on the list)Build a new header such that items are capitalized (with
str.join)
Solution to Exercise 9
items = myheader.split(";")
items
['wind', 'temperature', 'pressure']
items.append("Snow level")
items[0] = items[0].capitalize()
items[1] = items[1].capitalize()
items[2] = items[2].capitalize()
items
['Wind', 'Temperature', 'Pressure', 'Snow level']
";".join(items)
'Wind;Temperature;Pressure;Snow level'