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
“box” using primes[index]
.
For example, the statement “print(primes[3])
”
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.
While 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.
The len
function returns the list length:
len(primes)
is 5.
The +
operator can add two lists together to create
a new list:
primes + [13]
leads to the list [2, 3, 5, 7, 11, 13]
(though primes
doesn't change).
The *
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
the list: primes[2]
is 5.
And you can include a colon to pull out a sub-list of multiple
items 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[0] = 17
There are several functions helpful for dealing with lists.
code | result |
len(x) |
the number of entries in x |
max(x) |
the maximum value in x |
min(x) |
the minimum value in x |
sorted(x) |
a sequence with the same entries as x but in increasing order |
sum(x) |
the sum of all the numbers in x |
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[0])) # displays 3
days_sort = sorted(days)
print(days_sort[0]) # displays Fri