# Unit 4: Lists

A list is an ordered collection of values. The values that make up a list are called its elements, or its items.

## List values

There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):

```>>> ps = [10, 20, 30, 40]
>>> qs = ["spam", "bungee", "swallow"]
```

The first example is a list of four integers. The second is a list of three strings.

Finally, a list with no elements is called an empty list, and is denoted [].

We have already seen that we can assign list values to variables or pass lists as parameters to functions:

```>>> vocabulary = ["apple", "cheese", "dog"]
>>> numbers = [17, 123]
>>> an_empty_list = []
>>> print(vocabulary, numbers, an_empty_list)
["apple", "cheese", "dog"] [17, 123] []
```

## Accessing elements

The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string — the index operator: []. The expression inside the brackets specifies the index. Remember that the indices start at 0:

```>>> numbers
17
```

Any expression evaluating to an integer can be used as an index:

```>>> numbers[9-8]
5
```

## List Traversal

A lot of computations involve processing a list one item at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end.

```>>> horsemen = ["war", "famine", "pestilence", "death"]
```
```>>> for h in horsemen:
>>>     print(h)
```

Each time through the loop, the next item in the list is assigned to the variable h. The loop continues until no list are left.

## List Length

The function len returns the length of a list, which is equal to the number of its elements. If you are going to use an integer index to access the list, it is a good idea to use this value as the upper bound of a loop instead of a constant. That way, if the size of the list changes, you won’t have to go through the program changing all the loops; they will work correctly for any size list:

```>>> horsemen = ["war", "famine", "pestilence", "death"]
```
```>>> for i in range(len(horsemen)):
>>>     print(horsemen[i])
```

## List Membership

in and not in are Boolean operators that test membership in a sequence. We used them previously with strings, but they also work with lists and other sequences:

```>>> horsemen = ["war", "famine", "pestilence", "death"]
>>> "pestilence" in horsemen evaluates to True
```
```>>> "debauchery" in horsemen evaluates to False
```
```>>> "debauchery" not in horsemen evaluates to True
```

## List Slices

The slice operations we saw previously with strings let us work with sublists: >>> a_list = ["a", "b", "c", "d", "e", "f"] >>> A_list[1:3] evalutes to ['b', 'c']

```>>> A_list[:4] evaluates to ['a', 'b', 'c', 'd']
```
```>>> A_list[3:] evaluates to ['d', 'e', 'f']
```
```>>> A_list[:] evaluates to ['a', 'b', 'c', 'd', 'e', 'f']
```

## The while statement

Here is a fragment of code that demonstrates the use of the while statement:

```>>> def sum_to(n):
>>>     """ Return the sum of 1+2+3 ... n """
>>>     ss  = 0
>>>     v = 1
>>>     while v <= n:
>>>         ss = ss + v
>>>         v = v + 1
>>>     return ss
```
```>>> # For your test suite
>>> test(sum_to(4) == 10)
>>> test(sum_to(1000) == 500500)
```

It means, while v is less than or equal to n, continue executing the body of the loop. Within the body, each time, increment v. When v passes n, return your accumulated sum.

More formally, here is precise flow of execution for a while statement:

• Evaluate the condition at line 5, yielding a value which is either False or True.
• If the value is False, exit the while statement and continue execution at the next statement (line 8 in this case).
• If the value is True, execute each of the statements in the body (lines 6 and 7) and then go back to the while statement at line 5.

The body consists of all of the statements indented below the while keyword.

Notice that if the loop condition is False the first time we get loop, the statements in the body of the loop are never executed.

## The For statement

What you will notice here is that the while loop is more work for you — the programmer — than the equivalent for loop. When using a while loop one has to manage the loop variable yourself: give it an initial value, test for completion, and then make sure you change something in the body so that the loop terminates. By comparison, here is an equivalent function that uses for instead:

```>>> def sum_to(n):
>>>     """ Return the sum of 1+2+3 ... n """
>>>     ss  = 0
>>>     for v in range(n+1):
>>>         ss = ss + v
>>>     return ss
```