# Lists

Sue Evans

Hit the space bar for next slide

# Learning Outcomes

• Be aware that multiple items can be stored in a list.
• Become acquainted with Python's built-in functions, methods and operators that can be used for lists.
• Know the syntax of working with lists and items in a list.
• Understand that for loops are used to iterate over sequences, including lists.

# What's a List

• Definition:
• A list is an ordered collection of items, where the items can be of any type.
• Each item has a numerical index, indicating the position in the list, which is what is meant by "ordered". Indices start at zero.
• Operations:
• adding items to the list
• removing items from the list
• finding items in the list
• indexing (accessing or replacing an item in the list)

# Lists vs. Arrays

You may think that a list in Python is the same as an array in C or other languages. They are similar but there are some significant differences.

1. Although you may have arrays of any type, arrays are homogeneous, meaning they can only hold data of one type. Python lists are heterogeneous. The type of the data being stored can be different at different indices in the same list.
2. Arrays are a fixed size, but lists shrink and grow as necessary to hold the exact number of items being stored.

# Indexing

Indexing of lists in Python is similar to indexing of arrays.

Indices begin with 0.
For a list of length n, the last index will be n - 1.

Here's how we can picture a list of length 5, showing indices of 0 through 4.

0 1 2 3 4

Python allows us to use negative indices into a list, as well as positive ones.

The index -1 can be used to access the last item in the list.
The next to the last item can be accessed by using the index, -2, etc.

# Lists in Python

There are several ways to create new lists:

```>>> # assign the literal empty list
>>> empty = []
>>> empty
[]

>>> # use the list constructor
>>> empty = list()
>>> empty
[]

>>> # give a literal assignment of items
>>> items = ["bread", "milk", "cheese", "cider"]
>>> #         0        1       2         3
>>> items

>>> # use the list constructor with a string
>>> letters = list("hello")
>>> letters
['h', 'e', 'l', 'l', 'o']

>>> # use split which returns a list of strings
>>> words = "a bunch of words".split()
>>> words
['a', 'bunch', 'of', 'words']
```

Operators:

• indexing   list[index] - get or set an item at the given index in the list
```>>> items[2]
'cheese'
>>> items[3]
'cider'
>>> items[3]
```
• containment   item in list - see if the item is in the list
```>>> "milk" in items
True
>>> "juice" in items
False
```
• equality list1 == list2 - see if two lists are the same
```>>> "two words".split() == ["two", "words"]
True
>>> ["this", "that"] == ["that", "this"]
False
```

Methods:

• append(item) - add the item to end of the list
• count(item) - count occurences of the item in the list
• extend(list) - append multiple items to the end of the list
• index(item) - locate the index of an item in the list
• insert(index, item) - insert an item before the one at the index
• remove(item) - remove the first occurence of the item in the list
• reverse() - reverse the order of the items in the list
• sort() - sort the list

Built-in functions that operate on lists:

• len(list) - count number of items in the list
• del(list[index]) - remove the item at index from the list

# Examples

### List Methods

append(item) - add an item to the end of the list

```>>> items
>>> items.append('ham')
>>> items
>>> items.append('ham')
>>> items
>>>
```

count(item) - count occurences of an item in the list

```>>> items
>>> items.count('ham')
2
>>> items.count('cheese')
1
>>>
```

remove(item) - remove the first occurence of an item in the list

```>>> items
>>> items.remove('ham')
>>> items
>>>
```

extend(list) - append multiple items to end of the list

```>>> items.extend(['lettuce', 'tomatoes'])
>>> items
>>>
```

index(item) - locate the index of an item in the list

```>>> items
>>> items.index('milk')
1
>>>
```

insert(index, item) - insert an item before the one at the index

```>>> items
>>> items.insert(2, 'eggs')
>>> items
>>>
```

reverse() - reverse the order of the items in the list

```>>> items
>>> items.reverse()
>>> items
>>>
```

sort() - sort the list

```>>> items
>>> items.sort()
>>> items
>>>
```

### Built-In Functions

len(list) - count number of items in the list

```>>> items
>>> len(items)
8
>>>
```

del(list[index]) - remove the item at the index from the list

```>>> items
>>> del(items[4])
>>> items
['bread', 'cheese', 'eggs', 'ham', 'lettuce', 'milk', 'tomatoes']
>>>
```

# Using lists

Use a list when order matters.

• Items stay in the order they're inserted in with append()
• A list is indexed in order
• A list can also be changed so that the items are in sorted order.

# Iterating over sequences

• for loops can iterate over lists, strings and other sequences.
• We can iterate over elements in a list:
```>>> myList = [32, 45, 34, 76, 45]
>>> sum = 0.0
>>> for n in myList:
...    sum += n
...
>>> print sum / len(myList)
46.4
```
• range actually just generates a list:
```>>> print range(1,5)
[1, 2, 3, 4]
```
• We can iterate character by character through a string. Let's add a space between each character:
```>>> word = "hello world"
>>> for c in word:
...     print c,
...
h e l l o   w o r l d
```

# Example using a List

This example shows:

• Placing your code in main()
• Building a list, beginning with an empty list, using append
• How does range() work ?
range() creates a list of numbers ranging from 0 to one less than the value passed to it.  So range(5) creates the following list of numbers: [0, 1, 2, 3, 4]
Unlike loop control variables in many other languages, if the command is: for i in range(10):, i only counts from 0 to 9. The value of i never becomes 10. The loop actually stops when the list of numbers has been exhausted.
• Iteration through a list using "in" instead of using range.
Python allows us to traverse the list without specifying the index. This is more efficient and should be used instead of using range() whenever possible.
```
def main():

# Begin with an empty list
gpas = []

# Builds a list of 20 GPAs
for i in range(20):
gpa = input("Enter a student's GPA : ")
gpas.append(gpa)

# Initialize the accumulator
total = 0.0

# Can use "in" instead of range
for gpa in gpas:
# Accumulate into total
total += gpa

# Calculate average (total is already a float)
average = total / len(gpas)

print "The average GPA of this section is ", average

main()
```

Here's the output

```linuxserver1.cs.umbc.edu[132] python list.py
Enter a student's GPA : 3.0
Enter a student's GPA : 3.5
Enter a student's GPA : 2.0
Enter a student's GPA : 2.5
Enter a student's GPA : 1.5
Enter a student's GPA : 4.0
Enter a student's GPA : 2.7
Enter a student's GPA : 2.8
Enter a student's GPA : 3.2
Enter a student's GPA : 3.4
Enter a student's GPA : 2.2
Enter a student's GPA : 2.4
Enter a student's GPA : 1.9
Enter a student's GPA : 2.1
Enter a student's GPA : 2.8
Enter a student's GPA : 2.7
Enter a student's GPA : 3.3
Enter a student's GPA : 3.8
Enter a student's GPA : 3.4
Enter a student's GPA : 3.0
The average GPA of this section is 2.81
linuxserver1.cs.umbc.edu[133]
```

# The Improved List Example

The user needs to understand what the program is doing, so it's important that you always print a greeting.

An important step in coding is to make sure the data structure you are using (in this case a list), gets populated (in this case with the data being entered by the user).

```
def main():

# Tell the user what the program will do - Give a Greeting
print "This program will find the average GPA for a section of 201"
print

# Begin with an empty list
gpas = []

# Builds a list of 20 GPAs
for i in range(20):
gpa = input("Enter a student's GPA : ")
gpas.append(gpa)

# Mandatory Debugging Step - Make sure you really made a list!
# to be removed later
for i in range(20):
print "gpas[", i, "] = ", gpas[i]

# Initialize the accumulator
total = 0.0

# Can use "in" instead of range
for gpa in gpas:
# Accumulate into total
total += gpa

# Calculate average (total is already a float)
average = total / len(gpas)

# Add a blank line to separate the input from the result
print "\nThe average GPA of this section is ", average

main()
```
```This program will find the average GPA for a section of 201

Enter a student's GPA : 3.0
Enter a student's GPA : 3.5
Enter a student's GPA : 2.0
Enter a student's GPA : 2.5
Enter a student's GPA : 1.5
Enter a student's GPA : 4.0
Enter a student's GPA : 2.7
Enter a student's GPA : 2.8
Enter a student's GPA : 3.2
Enter a student's GPA : 3.4
Enter a student's GPA : 2.2
Enter a student's GPA : 2.4
Enter a student's GPA : 1.9
Enter a student's GPA : 2.1
Enter a student's GPA : 2.8
Enter a student's GPA : 2.7
Enter a student's GPA : 3.3
Enter a student's GPA : 3.8
Enter a student's GPA : 3.4
Enter a student's GPA : 3.0
gpas[ 0 ] =  3.0
gpas[ 1 ] =  3.5
gpas[ 2 ] =  2.0
gpas[ 3 ] =  2.5
gpas[ 4 ] =  1.5
gpas[ 5 ] =  4.0
gpas[ 6 ] =  2.7
gpas[ 7 ] =  2.8
gpas[ 8 ] =  3.2
gpas[ 9 ] =  3.4
gpas[ 10 ] =  2.2
gpas[ 11 ] =  2.4
gpas[ 12 ] =  1.9
gpas[ 13 ] =  2.1
gpas[ 14 ] =  2.8
gpas[ 15 ] =  2.7
gpas[ 16 ] =  3.3
gpas[ 17 ] =  3.8
gpas[ 18 ] =  3.4
gpas[ 19 ] =  3.0

The average GPA of this section is  2.81

```

Now that we know the data being entered is actually being stored in the list, we can remove the debugging loop that prints the list, producing:

```This program will find the average GPA for a section of 201

Enter a student's GPA : 3.0
Enter a student's GPA : 3.5
Enter a student's GPA : 2.0
Enter a student's GPA : 2.5
Enter a student's GPA : 1.5
Enter a student's GPA : 4.0
Enter a student's GPA : 2.7
Enter a student's GPA : 2.8
Enter a student's GPA : 3.2
Enter a student's GPA : 3.4
Enter a student's GPA : 2.2
Enter a student's GPA : 2.4
Enter a student's GPA : 1.9
Enter a student's GPA : 2.1
Enter a student's GPA : 2.8
Enter a student's GPA : 2.7
Enter a student's GPA : 3.3
Enter a student's GPA : 3.8
Enter a student's GPA : 3.4
Enter a student's GPA : 3.0

The average GPA of this section is  2.81
```

# List Exercise

In your groups, write Python code that will:

• get 10 integers from the user and store them in a list
• find the total of the numbers in the list
• find the minimum value in the list
• find the maximum value in the list
• find the average of the values in the list
• print the total, minimum, maximum & average similar to the following sample output:
```Total = 115
Minimum = 1
Maximum = 25
Average = 11.5
```
• your code should be in main()
• check to make sure your list is populated using a mandatory debugging statement