Often programs need to work with large groups of related data. A list is a useful type for storing a sequence of values. You can think of a list as a sequence of boxes, each storing their own value. Here is an example.
0 1 2 3 4 2 3 5 7 11
In Python, we can create this list by enclosing the
elements in brackets, separated by commas.
Let's set the variable
primes to refer to this list.
primes = [2, 3, 5, 7, 11]
Each “box” in the list has its own index,
starting from 0, and we can reference a particular
For example, the statement “
would display 7.
Look familiar? A list is closely related to a string. The
biggest difference is that a string holds characters only,
whereas lists can hold any type of value at all.
primes holds a list of integers,
you could easily have a list of strings,
a list of lists, or even a mixture of different types.
In fact, Python is admirably consistent: Everything that we've done with strings, you can also do with a list.
len function returns the list length:
len(primes) is 5.
+ operator can add two lists together to create
a new list:
primes +  leads to the list [2, 3, 5, 7, 11, 13]
primes doesn't change).
* operator can multiply an integer by a list to
create a new list with several copies of the original:
3 * [0, 1] results in [0, 1, 0, 1, 0, 1].
Finally, the brackets can pull out an individual item from
primes is 5.
And you can include a colon to pull out a sub-list of multiple
primes[1:4] is the list [3, 5, 7].
But the list allows some more things, too. Most notably, a list can change. The following example would replace the 2 with 17.
primes = 17
There are several functions helpful for dealing with lists.
||the number of entries in
||the maximum value in
||the minimum value in
||a sequence with the same entries as
||the sum of all the numbers in
The following examples illustrate these functions at work.
print(sum(primes)) # displays 43 (from 17 + 3 + 5 + 7 + 11)
print(min(primes)) # displays 3
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for i in range(len(days)):
print(days[i]) # displays each day name on separate line
print(len(days)) # displays 7
print(len(days)) # displays 3
days_sort = sorted(days)
print(days_sort) # displays Fri