CSci 150: Foundations of computer science
Home Syllabus Readings Projects Tests


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.


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 = [235711]

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.

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.

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