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#
l = [0, 1, 2, 3, 4, 5]
l1 = l[:] # shallow copy of l (same as `l1 = l.copy()`)
l1.append("a")
print(l1)
print(l)
[0, 1, 2, 3, 4, 5, 'a']
[0, 1, 2, 3, 4, 5]
References and del keyword (“delete”)#
del removes a reference. If an object in not bound to any names, Python can delete it
from its internal memory.
l = ["a", "b"]
del l[1]
print(l)
['a']
More on slicing#
Very general, can be used on all sequences as str, list, etc… Not simple for
beginners but very powerfull (see
here and
here).
Python indexes and slices for a six-element str. Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1
Index from front: 0 1 2 3 4 5
+---+---+---+---+---+---+
| a | b | c | d | e | f |
+---+---+---+---+---+---+
Slice from front: 0 1 2 3 4 5 6
Slice from rear: -6 -5 -4 -3 -2 -1 0
s = "abcdef"
# s[start:stop:step]
s[2:6:2]
'ce'
Other examples of slices for a six-element list. Indexes enumerate the elements, slices enumerate the spaces between the elements.
a = [0, 1, 2, 3, 4, 5]
all(
[
len(a) == 6,
a[1:] == [1, 2, 3, 4, 5],
a[:5] == [0, 1, 2, 3, 4],
a[0] == 0,
a[:-2] == [0, 1, 2, 3],
a[5] == 5,
a[1:2] == [1],
a[-1] == 5,
a[1:-1] == [1, 2, 3, 4],
a[-2] == 4,
]
)
True
Built-in: slice#
In python, the built in slice is another way to access elements of sequence:
sl_2_elems = slice(0, 2) # get the first two elements
print(a[sl_2_elems])
last_elems = slice(2, None) # get the last elements
print(a[last_elems])
[0, 1]
[2, 3, 4, 5]
If the same slice is used at different part of the code, then storing a slice object and reusing it elsewhere might be more practical than rewriting the slice each time.
Exercise 8
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 8
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'