## Jason M. Grant

Assistant Professor of Computer Science

## Iteration and Lists

### What are Lists?

Lists are mutable, ordered sequence of elements. Mutable simply means that the contents inside of it can be changed. Ordered tells us that when we add items to our list, we can be assured of the order in which they are stored in the list. We will look at other data structures later in the semester that are unordered.

How do we makea list?

1. Using the built-in constructor

`a_new_list = list()`

or

`a_new_list = list([element1, element2,...])`

2. Using the shorthand display notation (hard brackets)

`a_new_list = []`

or

`a_new_list = [element1, element2,...]`

3. Using a list comprehension

`a_new_list = list(expression for variable in sequence)`

or

`a_new_list = [expression for variable in sequence]`

Essentially, you can place a for-loop inside of a list. We will talk more about this later!

What can we place insideof a list?

Anything, as long as it is a valid Python expression. For example,

`L = [ 5, 10, 'Hello', 5 < 3, 5+3, 'c'*3 ]`

is valid syntax and evaluates to

`[ 5, 10, 'Hello', False, 8, 'ccc' ]`

You can even put a list inside of a list! An example would be

`a_new_list = [ 5, 10, [‘the’, ‘inner’, ‘list’], 8, ‘ccc’ ]`

How do we access items in a list? This is very similar to the way we access characters in a string. We refer to this as indexing. For example, lets look at a list called stuff.

`stuff = ['cat', 'dog', 10, 20, True]`

This list contains two strings, two integers, and a boolean. When can quickly find out how many items are in a list using the `len()`function. If you remember, this is the same function we used to find out how many elements there were in a string.

This lists has 5 elements. Therefore the indices go from 0 to 4.

`>>> stuff[0]'cat'>>> stuff[4]True>>> stuff[1:4]['dog', 10, 20]`

What if we had a nested list, a list inside of a list? How would we access those elements?

`>>> more_stuff = [5, 10, ['the', 'inner', 'list'], 8, 'ccc']>>> more_stuff[2]['the', 'inner', 'list']>>> more_stuff[2][1]'inner'`

Lists are mutual meaning you can change the contents of an item in a list. Let’s look at adding and removing items from a list. Items are added to the end of a list using the `append()`function. For example:

`>>> more_stuff.append('new item')[5, 10, ['the', 'inner', 'list'], 8, 'ccc', 'new item']`

We can also remove items from a list. Two simple ways to remove items are using the `remove()`function, which searches for an item and removes it from the list, and the `pop()`function, which removes the last item from the list and returns it.

`>>> len(more_stuff)6>>> more_stuff.remove(5)>>> len(more_stuff)5>>> more_stuff.pop()'new item'>>> len(more_stuff)4`