Lists
More precisely, we can define a sequence as a finite and ordered set of elements.
There are two types of sequences in Python: tuples and lists.
Lists
Lists have several properties:
- list elements are placed between brackets:
[val1, val2, val3]
- lists are ordered, each element is associated with an index
- lists are modifiable
- list elements can be of different types: you can combine strings, integers, objects, in the same list
Lists, like tuples, are sequences. They are therefore manipulated in the same way. However, we can add two elements related to the mutable character of lists: it is possible to delete or add elements to a list, but also to modify elements directly.
my_list = [14, "fish", 42, True]
print(type(my_list), ":", my_list)
print(type(my_list[0]), ":", my_list[0])
print(type(my_list[1]), ":", my_list[1])
print(type(my_list[2]), ":", my_list[2])
print(type(my_list[3]), ":", my_list[3])
# modify an element
my_list[1] = "frog"
print(my_list)
# add an element
my_list.append(1988)
print(my_list)
# delete an element
del my_list[4]
print(my_list)
# length of a list
print("There are", len(my_list), "elements in the list")
<class 'list'> : [14, 'fish', 42, True]
<class 'int'> : 14
<class 'str'> : fish
<class 'int'> : 42
<class 'bool'> : True
[14, 'frog', 42, True]
[14, 'frog', 42, True, 1988]
[14, 'frog', 42, True]
There are 4 elements in the list
good to know
- the
del
instruction allows deleting an element from a list - the my_list.
append()
function allows adding an element to the end of a list - the
len()
function allows getting the length of a tuple or list - you can modify a list:
list[2] = "house"
- operations on tuples are slightly faster: if you know you won't need to modify your sequence, prefer tuple to list
Traversing a sequence: for loop
We briefly saw the for
keyword, particularly its use in combination with the range()
function. Thus, we were able to perform iterations on a defined number of elements.
The for instruction also allows traversing sequences: typically, tuples or lists! The structure is identical to using range()
, and here's an example:
# creating a list, this works the same way with a tuple
prime_numbers = [1, 3, 5, 7, 11, 13, 17]
for nb in prime_numbers:
print(nb, "is a prime number.")
1 is a prime number.
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
::