Introduction

Many programming tasks require the programmer to manipulate data in many ways. Often, we are given a finite set of data and must perform some sort of operation on it (arithmetic, sorting, etc.). Let’s look at one way to handle sets of information in Python.

Let’s say we’re given a grocery list, and told to store it into a single variable, groceryList. Python has a built in data type called a List. If you’re familiar with arrays, you can treat these two terms the same (for now).

Here’s my grocery list:

• Apples
• Milk
• Eggs
• Cheese

It is easy to see that the individual elements here are best stored as String values. Python’s List type gives us a great way to store all of the individual elements together. A Python List is defined between two square brackets “[ ]” and items are separated by a comma “,”. Let’s make a grocery list!

groceryList = ["Apples", "Milk", "Eggs", "Cheese"]

Now if we ask Python to print groceryList, we see that it shows

['Apples', 'Milk', 'Eggs', 'Cheese']

Note that Lists can store more than String data types. They can store Integers, Floats, Booleans, other Lists, and more!

This is the basic concept of Lists. Let’s see what else we can do with them.

List Elements

An element is one entry in any list in Python. From the above example, “Apple” is an element. So is “Milk”, “Eggs”, and “Cheese”.

A list can contain zero to many elements. You could store more and more elements in a list until your computer ran out of memory! You can also choose to store no elements in a list. This is called “the empty list”, which is declared by entering no elements in a new list.

emptyList = []

Append

Elements can also be added, changed, or removed after the list is initially declared. There are several ways to do this, but let’s start with something simple.

Python’s append() function adds an element to the end of a list. Let’s try to add an element to the empty list!

emptyList = []                      #List is empty
print "empty:    " , emptyList      #Print empty list
emptyList.append("An Element!")     #Add element to empty list
print "nonempty: " , emptyList      #Print nonempty list

Before we look at the output, I’d like to touch briefly on a few important things in this code.

1. In Python, when we want to perform some function on a variable (in this case, emptyList), we often notate it as object.method(arguments). This tells Python to perform a some task with the arguments as its input. We can see here how we appended the string “An Element!” to the variable emptyList by emptyList.append(“An Element!”).

2. As you’ve probably seen in class and lab, a comma can be used during a print statement to print two different values on the same line. In the above example, we are able to organize our output by using the comma.

Now let’s look at the output:

empty: []
nonempty: ['An Element!']

We can see that the list is no longer empty. Remember that the append statement always adds the new element to the end of the list. Let’s say we forgot an item in our grocery list and wish to add it later.

groceryList = ["Apples", "Milk", "Eggs", "Cheese"]

groceryList.append("Flour")
print groceryList

We see the new list:

['Apples', 'Milk', 'Eggs', 'Cheese', 'Flour']

Now we’ve successfully added “Flour” to our list.

Index Access

Our list currently has five elements; but some lists will have hundreds, even thousands of elements. How can we possibly deal with all this data? One way is to deal with each value by index. An index is a numerical representation of the position of an element in a list. Remember that in programming, we usually start counting at zero.

Element: ["Apples", "Milk", "Eggs", "Cheese", "Flour"]
Index:   [  0,        1,      2,       3,        4   ]

We can see now that given the array above, we can say that:

• “Apples” is located in index 0
• “Milk” is located in index 1

And so on.

To access an array element by its index, we use the following notation:

element = array[index]

So, using our grocery list example, let’s access the element “Cheese” by index.

groceryList = ["Apples", "Milk", "Eggs", "Cheese"]
element = groceryList  # cheese

Remember that we choose  instead of  because our first index is at  instead of .

Array (List) Loops

Often, we are given a large set of data and must perform some operation on it. In many cases, the same operation must be performed on each element in the array. Let’s say our data is a collection of numbers whose sum we want to determine. Remember from Tutorial 02 that we want to avoid repeating ourselves (adding each element using a separate line of code), and should thus use a FOR loop.

In this example, we will calculate the sum of a list of numbers.

sum = 0
numbers = [1, 2, 5, 80, 231, 0, 19, 4]

We need the FOR loop to run for each element in the list. We know the list has 8 elements, so our index values will go from 0 to 7. Recall from Tutorial 02 that this means we should use range(0, 8).

sum = 0
numbers = [1, 2, 5, 80, 231, 0, 19, 4]

for i in range(0, 8):  # <-
# Do something

Here’s where the i variable in our FOR loop (the index variable) becomes very handy. Since our value of i will change during each loop iteration, and will take the value of all integers from 0 to 7, we can use this value to access our list!

sum = 0
numbers = [1, 2, 5, 80, 231, 0, 19, 4]

for i in range(0, 8):
value = numbers[i]  # <-

Now each time the loop iterates (and i changes), we want to add the value at index i to our sum:

sum = 0
numbers = [1, 2, 5, 80, 231, 0, 19, 4]

for i in range(0, 8):
value = numbers[i]
sum = sum + value    # <-

Now we want to print our result. To avoid printing the current result many times, we place the print statement outside the loop.

sum = 0
numbers = [1, 2, 5, 80, 231, 0, 19, 4]

for i in range(0, 8):
value = numbers[i]
sum = sum + value
print sum                # <-

And our output:

342

This is correct! We have successfully iterated through a List using a FOR loop.

List Methods

Python has many built-in functions to modify lists. These are called Methods. We saw the append() function earlier. Let’s look at some other examples of useful list methods.

Method: list.reverse()

Reverses the elements of a list in place.

myList = [1, 2, 3, 4, 5]
myList.reverse()
print myList

Output:

[5, 4, 3, 2, 1]

Method: list.insert()

Takes two arguments list.insert(x, y) where x is the index to insert the value y. All other elements are shifted up one index, none are replaced.

myList = [1, 2, 3, 4, 5]
myList.insert(2, 2.5)
print myList

Output:

[1, 2, 2.5, 3, 4, 5]

Function: len()

len() is a normal function, not a List method. The reason I am mentioning it here is because it can be very useful in determining the number of elements in an array, which can be used to set the range(x, y) limits of your FOR loop.

myList = [1, 2, 3, 4, 5] l = len(myList) # Use like a normal function, not a method.
print l

Output:

5

There are 6 elements in this list. Therefore, we can use the range

range(0, 6)

But it would clearly be better to use

range(0, len(myList))

in a FOR loop. This ensures the loop starts at 0 (the first index) and iterates through all elements in the list.