= [2, 1, 3]
l l
[2, 1, 3]
Marie-Hélène Burle
Values can be stored in collections. This section introduces tuples, dictionaries, sets, and arrays in Python.
Lists are declared in square brackets:
They are mutable:
Lists are ordered:
They can have repeat values:
Lists can be homogeneous:
or heterogeneous:
They can even be nested:
The length of a list is the number of items it contains and can be obtained with the function len
:
To extract an item from a list, you index it:
Python starts indexing at 0
, so what we tend to think of as the “first” element of a list is for Python the “zeroth” element.
# Of course you can't extract items that don't exist
[3, ['b', 'e', 3.9, ['some string', 9.9]], 8][3]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[15], line 2 1 # Of course you can't extract items that don't exist ----> 2 [3, ['b', 'e', 3.9, ['some string', 9.9]], 8][3] IndexError: list index out of range
You can index from the end of the list with negative values (here you start at -1
for the last element):
Your turn:
How could you extract the string 'some string'
from the list [3, ['b', 'e', 3.9, ['some string', 9.9]], 8]
?
You can also slice a list:
Notice how slicing returns a list.
Notice also how the left index is included but the right index excluded.
If you omit the first index, the slice starts at the beginning of the list:
If you omit the second index, the slice goes to the end of the list:
When slicing, you can specify the stride:
The default stride is 1
:
You can reverse the order of a list with a -1
stride applied on the whole list:
You can test whether an item is in a list:
or not in a list:
You can get the index (position) of an item inside a list:
Note that this only returns the index of the first occurrence:
Lists are mutable (they can be modified). For instance, you can replace items in a list by other items:
You can delete items from a list using their indices with list.pop
:
Here, because we are using list.pop
, 2
represents the index (the 3rd item).
or with del
:
You can also delete items from a list using their values with list.remove
:
Here, because we are using list.remove
, 2
is the value 2
.
Notice how a list can even be empty:
You can actually initialise empty lists:
You can add items to a list. One at a time:
And if you want to add multiple items at once?
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[37], line 2 1 # This doesn't work... ----> 2 L.append(3, 6, 9) TypeError: list.append() takes exactly one argument (3 given)
Your turn:
Fix this mistake we just made and remove the nested list [3, 6, 9]
.
To add multiple values to a list (and not a nested list), you need to use list.extend
:
If you don’t want to add an item at the end of a list, you can use list.insert(<index>, <object>)
:
Your turn:
Let’s have the following list:
Insert the string 'nested'
in the zeroth position of the nested list [3, 6, 9]
in L
.
You can sort an homogeneous list:
Heterogeneous lists cannot be sorted:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[45], line 2 1 L = [3, ['b', 'e', 3.9, ['some string', 9.9]], 8] ----> 2 L.sort() TypeError: '<' not supported between instances of 'list' and 'int'
You can also get the min and max value of homogeneous lists:
For heterogeneous lists, this also doesn’t work:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[48], line 1 ----> 1 min([3, ['b', 'e', 3.9, ['some string', 9.9]], 8]) TypeError: '<' not supported between instances of 'list' and 'int'
Lists can be concatenated with +
:
or repeated with *
:
[3,
['b', 'e', 3.9, ['some string', 9.9]],
8,
3,
['b', 'e', 3.9, ['some string', 9.9]],
8,
3,
['b', 'e', 3.9, ['some string', 9.9]],
8]
To sum up, lists are declared in square brackets. They are mutable, ordered (thus indexable), and possibly heterogeneous collections of values.
Strings behave (a little) like lists of characters in that they have a length (the number of characters):
They have a min and a max:
You can index them:
Slice them:
Your turn:
Reverse the order of the string S
.
They can also be concatenated with +
:
or repeated with *
:
This is where the similarities stop however: methods such as list.sort
, list.append
, etc. will not work on strings.
Python comes with a built-in array module. When you need arrays for storing and retrieving data, this module is perfectly suitable and extremely lightweight. This tutorial covers the syntax in detail.
Whenever you plan on performing calculations on your data however (which is the vast majority of cases), you should instead use the NumPy package, covered in another section.
Tuples are defined with parentheses:
Tuples are ordered:
This means that they are indexable and sliceable:
They can be nested:
They can be heterogeneous:
You can create empty tuples:
You can also create singleton tuples, but the syntax is a bit odd:
However, the big difference with lists is that tuples are immutable:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[71], line 2 1 T = (2, 5) ----> 2 T[0] = 8 TypeError: 'tuple' object does not support item assignment
Tuples are quite fascinating:
Tuples are declared in parentheses. They are immutable, ordered (thus indexable), and possibly heterogeneous collections of values.
Sets are declared in curly braces:
Sets are unordered:
Consequently, it makes no sense to index a set.
Sets can be heterogeneous:
There are no duplicates in a set:
You can define an empty set, but only with the set
function (because empty curly braces define a dictionary):
Since strings an iterables, you can use set
to get a set of the unique characters:
Your turn:
How could you create a set with the single element 'abba'
in it?
Sets are declared in curly brackets. They are mutable, unordered (thus non indexable), possibly heterogeneous collections of unique values.
Dictionaries are declared in curly braces. They associate values to keys:
Dictionaries are unordered:
Consequently, the pairs themselves cannot be indexed. However, you can access values in a dictionary from their keys:
To return a sorted list of keys:
You can create empty dictionaries:
Dictionaries are mutable, so you can add, remove, or replace items.
Let’s add an item to our empty dictionary E
:
We can add another one:
We can modify one:
Your turn:
Add a third item to E with the number of volumes.
We can also remove items:
Another method to remove items:
Dictionaries are declared in curly braces. They are mutable and unordered collections of key/value pairs. They play the role of an associative array.
From tuple to list:
From tuple to set:
From list to tuple:
From list to set:
From set to tuple:
From set to list:
Python has a built-in collections module providing the additional data structures: deque, defaultdict, namedtuple, OrderedDict, Counter, ChainMap, UserDict, UserList, and UserList.