Iteration

Our other aspect of control is iteration.

Imagine if we had a list, and wanted to check if all the elements were positive.

Using what we have learnt so far, we might write something like this:

mylist = [3, 7, 15, 2]

if mylist[0] > 0:
    print ("first element is positive")
if mylist[1] > 0:
    print ("second element is positive")
if mylist[2] > 0:
    print ("third element is positive")
if mylist[3] > 0:
    print ("fourth element is positive")

We can see that this isn’t a very efficient way of doing this.

A better way would be to use iteration - loops.

We use forin to “iterate” over lists. The above, can be re-written as:

mylist = [3, 7, 15, 2]

for element in mylist:
    if element > 0:
       print "List item " element " is positive"

Each time through the loop, the variable in the value slot is updated to the next element of the sequence.

Another example is:

mylist = [3, 7, 15, 2]
for element in mylist:
    print(element**2)

9

49

225

4

Iterables

Any sequence type is iterable:

vowels = "aeiou"

sarcasm = []

for letter in "Okay":
    if letter.lower() in vowels:
        repetition = 3
    else:
        repetition = 1
    sarcasm.append(letter*repetition)

"".join(sarcasm)

‘OOOkaaay’

The above is a little puzzle, work through it to understand why it does what it does.

Dictionaries are Iterables

All sequences are iterables. Some iterables (things you can for loop over) are not sequences (things with you can do x[5] to), for example sets.

import datetime
now = datetime.datetime.now()

founded = {"John": 1976, "UCL": 1826, "Cambridge": 1209}

current_year = now.year

for x in founded:
    print(x, " is ", current_year -  founded[x], "years old.")

UCL is 192 years old.

Cambridge is 809 years old.

John is 42 years old.

In the above example we accessed the values by iteration of the keys, for each iteration this the equivalent of the example below:

thing = "UCL"

founded[thing]

1826

Let’s consider our dictionary:

founded

{‘Cambridge’: 1209, ‘John’: 1976, ‘UCL’: 1826}

This is constructed from key value pair tuples:

founded.items()

dict_items([(‘UCL’, 1826), (‘Cambridge’, 1209), (‘John’, 1976)])

and can therefore be unpacked.

Unpacking and Iteration

Unpacking can be useful with iteration:

triples = [
    [4,11,15],
    [39,4,18]
]
for whatever in triples:
    print(whatever)

[4, 11, 15]

[39, 4, 18]

We can unpack lists:

a,b = [36, 7]
b

7

for first, middle, last in triples:
    print(middle)

11

4

# A reminder that the words you use for variable names are arbitrary:
for hedgehog, badger, fox in triples:
    print(badger)

11

4

For example, to iterate over the items in a dictionary as pairs:

for name, year in founded.items():
    print(name, " is ", current_year - year, "years old.")

UCL is 191 years old. Cambridge is 808 years old. John is 41 years old.

for name in founded:
    print(name, " is ", current_year - founded[name], "years old.")

UCL is 192 years old.

Cambridge is 809 years old.

John is 42 years old.

Break, Continue

for n in range(50):
    if n == 20:
        break
    if n % 2 == 0: #check for even numbers
        continue
    print(n)

1

3

5

7

9

11

13

15

17

19

These aren’t useful that often, but are worth knowing about. There’s also an optional else clause on loops, executed only if you don’t break.

Next: Experience - Practical: Iteration