Definition: A list is a ordered sequence of possibly inhomogeneous elements. Python lists are the programmatic embodiement of the mathematical notion of $n$-tuple:
$$a = (a_1, a_2, \dots, a_n)\in A_1 \times A_2 \times \cdots \times A_n,$$where the $i^{th}$ element belongs to the set $A_i$ (the sets being $A_i$s potentially disticts).
In Python, one can use the same notation as in math, in which case the list elements won't be able to be modified after having been assigned. In the Python lingo, these constant lists are also called tuples.
In [ ]:
To create mutable list (i.e. a list whose elements can be further modified), Python uses square brackets instead of parenthesis:
In [ ]:
In math, one uses the subscript notation $a_i$ to denote the $i^{th}$ element of a list $a$. Instead of that notation, Python uses the square bracket operator (caution: in Python indices start at zero):
In [ ]:
In [ ]:
Observed that elements from a Python tuple can be retrived but not reassigned, as opposed to Python lists, which is why Python list are called mutable and Python tuples are called immutable:
In [ ]:
In [ ]:
In [ ]:
Algorithmically, one may be interseted in lists for various reasons:
looping over elements (as we have already seen)
retrieving sublists of a given lists
sorting the list elements according to a particular criterium
Sublists
One retrieves from a given Python's list, say my_list
, a sublist of consecutive indices by indicating the sublist range or "slice":
my_list[3:6]
returns the sublist
[my_list[3], my_list[4], my_list[5]]
In [ ]:
The function len(my_list)
returns the length of my_list
In [ ]:
my_list[-1]
is the last element of the list my_list[-2]
is the element before the last element, etc.Sorting
In [ ]:
In [ ]: