13: Lists (Arrays)

A list is a sequence of several variables, grouped together under a single name. Instead of writing a program with many variables x0, x1, x2, … you can define a single variable x and access its members x[0], x[1], x[2], etc. More importantly, you can put other expressions and variables inside the square brackets, like x[i] and x[i+1]. This allows us to deal with arbitrarily large data sets using just a single small piece of code.

One way to create a list is by enclosing several values, separated with commas, between square brackets:

myList = ["the first value in the list", 1999, 4.5]
This creates a list called myList of length 3. Each element of the list gets a number called its index: the initial element has index 0, the next element has index 1, and so forth. The individual variables comprising the list have the names


So in this example, myList[0] is a variable whose value is the string "the first value in the list" and print(myList[2]) would print 4.5. You can also change the values of items in the list, and print out entire lists:

Updating and printing a list.

As you can see, numbers[0] is treated as if it were itself a variable: it has a value and can be changed.

Next, try to predict the final state of the visualized example below, then compare it with actually running the code.

Multiple Choice Exercise: Meta-Stuff
What is the output of the following code fragment?

stuff = [2, 25, 80, 12]
stuff[stuff[0]] = stuff[3]
Correct! Look at the assignment statement (the 2nd line). The value of stuff[3] on the right side is 12. For the left side, stuff[0] is 2, so stuff[stuff[0]] refers to the variable stuff[2]. The value of this variable is updated (from 80) to 12.

What Python calls a list would be called an array in most other programming languages. Python also has something different & more advanced called arrays.

A Common Error

If you try to ask Python for an index that doesn't exist, it gives you an error:

Out-of-range error.

In the above example, because myList has length 4 and the first index is 0, the maximum possible index is 3. Asking for an index of 4, 5, or anything larger gives this kind of error.

Common Useful Operations

The Length of a List: len(«list»)

To determine the number of items in a list, call the function len() on that list. Look at how range is used in the following example.

Getting the length of a list and using it to iterate through the list.

It is common to use len to write code that can work on lists of any length, like in the example above, and in the next exercise.

Coding Exercise: Monkey in the Middle
Write a function middle(L) which takes a list L as its argument, and returns the item in the middle position of L. (In order that the middle is well-defined, you should assume that L has odd length.) For example, calling middle([8, 0, 100, 12, 1]) should return 100, since it is positioned exactly in the middle of the list.
Enter testing statements like print(myfunction("test argument")) below.

Are Lists Like Strings?

At this point, you might have noticed that the operations on lists are a lot like strings: both of them can be passed to the len() function to get their lengths, and both of them use X[«index»] to extract individual items. Lists and strings are indeed related: they are both "sequence types" in Python. The one major difference is that individual characters in strings cannot be changed.

Error caused by trying to assign a value to a character in a string.

For this reason lists are called a mutable type and strings are immutable; you will see a little more information about this in lesson 17.

Concatenation and Creation

From the lesson about the str type, you may remember that it is possible to use + to merge (concatenate) two strings together. You can do the same thing with lists:

Combining lists with +.

Similarly, you can use the multiplication symbol * to extend a list by repetition. This is useful for creating a new list of a desired length.

Using *.

To solve the next exercise, use one of the operators we just introduced, and a for loop.

Coding Exercise: It's Natural
Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.
Enter testing statements like print(myfunction("test argument")) below.

End of the Line: Negative Indices

To get the last item of a list, use


More generally, L[-k] returns the kth item from the end of the list; Python handles this internally by translating it to L[len(L)-k]. This shortcut notation works for strings too!

Coding Exercise: Palindrome
A palindrome is a word which is spelled the same forwards as backwards. For example, the word


is a palindrome: the first and last letters are the same (r), the second and second-last letters are the same (a), etc. Write a function isPalindrome(S) which takes a string S as input, and returns True if the string is a palindrome, and False otherwise.

Enter testing statements like print(myfunction("test argument")) below.

max and sum

The function max which we saw before can also be applied to a list of numbers: it returns the largest number in the list. Likewise, the function sum(L) returns the sum of the elements in list L.


Coding Exercise: Product
Define a function prod(L) which returns the product of the elements in a list L.
Enter testing statements like print(myfunction("test argument")) below.

Looping through lists

It is very common (like in the previous exercise) to loop through every value in a list. Python allows a shortcut to perform this type of an operation, usually called a "for all" loop or a "for each" loop. Specifically, when L is a list, this code

for x in L:
  «loop body block»
does the following: first x is set to the first value in L and the body is executed; then x is set to the second value in L and the body is executed; this is continued for all items in L.

Here is a visualized example of printing out the elements in a list:

Coding Exercise: for in
Define the function prod(L) as before, but this time using the new kind of loop.
Enter testing statements like print(myfunction("test argument")) below.

"For all" loops work for strings too: try for char in "hello".

Well done! you can proceed to the next lesson, or try some bonus exercises below.

Short Answer Exercise: Mystery Function
What is the value of x which will cause mystery(x) to run forever?

def mystery(x):
a = [0, 4, 0, 3, 2]
while x > 0:
x = a[x]
return "Done"

Scramble Exercise: à la Mode
The mode of a list is the element which occurs most frequently (the one which appears the maximum number of times). Unscramble the following program so that mode(L) correctly finds the mode, assuming L is a list of numbers from 0 to 9. (On our tests, there won't be two numbers tied for the maximum frequency.)
  • for i in range(0, 10):
  • for i in L:
  • return i
  • frequency[i] = frequency[i] + 1
  • frequency = [0]*10
  • if frequency[i]==max(frequency):
  • def mode(L):