CS 200: Lists in Python

This notebook mirrors the Google Python Course: Lists.

Video:

See Lists from Socratica.

Lists in python are sequences of objects, delimited by square brackets and separated by commas. Just as strings in python are sequences of characters. Strings have a length and can be indexed and sliced. Lists share these properties.

As you can see, lists pretty much behave as expected compared to strings.

for loops

We will often want to iterate over a list. That is, we will execute some code for each element of the list. One common way to do this in python is using a for loop.

In this example, the local variable element is bound to each successive element in the list l. We print out that element times 2. Note that for loop uses a colon (:) to specify the start of the code block to be executed for each element

Below we add up the numbers in a list.

We can write the addition and assignment more succinctly.

Alas, python does not have the wonderful autoincrement operator ++, found in C, Java, JavaScript, and, of course, C++.

in to test membership

The for loops above used in. We may also use in as a boolean (true/false) to test membership in a list.

enumerate function

When we iterate through a list, we sometimes want both the sequential values and the indices of the respective values. enumerate solves this problem.

enumerate returns an object which generates a list of tuples (index, element) We will look at tuples later on.

l now contains the squares of each former element in l. Let's try it again.

range() function

We often want list of sequential integers - usually the first n integers. range() does the job.

Note that range returns a range object which is a generator, not a list. We can convert the generator to a list using the list() construction for the list class.

Thus, range(10) produces the first 10 integers, starting with 0. We can provide a different start value than 0.

As with slices, we can also provide a different step value. If the step value is negative, the start must be bigger than the end.

while loop

In addition to the for loop, python has a while loop for iteration. The body of the loop is executed as long as the condition is true.

List Methods: append, extend, insert

list.append(element) - Adds a new element to the end of the list. Common error: does not return a copy, but modifies original list.

list.extend(list2) - Adds the elements of list2 to the end of list. Using += on a list is similar.

list.insert(index, element) - Inserts the element at the given index, shifting elements to the right.

More list methods: index, remove, sort, reverse

list.index(element) - return the index of the first occurence of element in the given list. If the element is not present, throws an error. You should test for membership with in first to avoid this error.

list.remove(element) - removes the first occurence of the given element from the list. Throws a ValueError if not present.

list.sort() - sorts the elements of the list in place. Does not return a copy. (The sorted() function below if preferred.)

list.reverse() - reverses the order of the list. Does not return a copy.

3 is l[3]. 9 is not an element of l.

l2.remove(3) removed just the first occurence of 3 in the list. The other two remain.

l was already sorted. When we sort l2, the list is changed.

sort has an optional parameter reverse which defaults to False. If you set it to True, you get the sort in descending order.

If you want to reverse the order of a list without sorting, you can use the reverse() method.

List methods: pop

list.pop() - removes and returns the tail element of the list. It is the opposite of append. If you pop an empty list, [], Python throws an error.

A common data structure is a stack which implements a Last In First Out (LIFO) process. You append (or push) items onto a stack and remove them with pop. We will implement stacks later on and also see that the Python interpreter (Python Virtual Machine) is itself implemented using a stack. There is world of pops in your future.

list mutations

You can assign new values to elements of lists.

End of lists notebook.