Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

More on for Loops

                          << Previous Tutorial           Next Tutorial >>
On this page: for ... in over list, string, dictionary. dict.items(), range(), nested for loops.

for Loops Over a List

As mentioned briefly in Tutorial 17, the for ... in loop is adaptive: you can use it with any sequence type (list, string, tuple) plus dictionaries. The most prototypical use of for ... in loop is over a list. Below, it is used to add up the numbers in a list:
>>> total = 0
>>> for n in [5.99, 12.99, 20.99, 129.99]: 
        total += n
        print 'Total is now', total

Total is now 5.99
Total is now 18.98
Total is now 39.97
Total is now 169.96		
>>> total  

for Loops Over a String

When used on a string, the looping has to go through every something. Well, a string is a sequence of characters, so the iteration is done on every character:
>>> for i in 'penguin': 
        print i  

for Loops Over a Dictionary

Naturally, we'd also want to be able to loop over a dictionary. When for ... in is used on a dictionary, looping is done over its keys, and not over the values or the key:value pairs:
>>> simpsons = {'Homer':36, 'Marge':35, 'Bart':10, 'Lisa':8}
>>> for s in simpsons:              # s iterates over keys in simpsons
        print s  
Of course, the values are retrievable via the keys. Hence, printing both the key and the value looks like:
>>> for s in simpsons:              # s iterates over keys in simpsons
        print s, simpsons[s]        # key, value  
Homer 36
Lisa 8
Marge 35
Bart 10 
An alternative is to explicitly instruct the for loop to iterate over the key:value pairs. The .items() method on a dictionary induces a list of (key, value) tuples. The for loop then can iterate over this list, and the bound variable should also be the tuple type:
>>> simpsons.items()             # returns a list of (key, value) pairs
[('Homer', 36), ('Lisa', 8), ('Marge', 35), ('Bart', 10)] 
>>> for (k,v) in simpsons.items():    # iterate over (key, value) list
        print k, v                    # key, value  
Homer 36
Lisa 8
Marge 35
Bart 10 
Note that the iteration is in no particular order, although it stays consistent. That's because dictionaries are inherently orderless. If you want to go through the dictionary in a particular order (say, alphabetical or numerical), you will have to sort. See Sorting for details.

Indexing With range() Function

range() is a function that's often used with a for loop. range(x,y) creates a list starting with integer x and ending BEFORE y. The starting point x can be omitted, in which case the list starts with 0:
>>> range(2,8)
[2, 3, 4, 5, 6, 7] 
>>> range(4)
[0, 1, 2, 3] 
The reason why range() is used often with a for loop is the following. In the 'penguin' example above, what if you want to also print out the index of each character? The way the loop is written, i is bound to the character itself, and there's nothing that references the location of an individual character. range() solves this. First, range() together with len('penguin') produces a list of indexes for the word:
>>> len('penguin')
>>> range(len('penguin'))
[0, 1, 2, 3, 4, 5, 6] 
Now, you can iterate through this list of indexes, and it is easy enough to get to the character once you have its index:
>>> for i in range(len('penguin')): 
        print i, 'penguin'[i] 
0 p
1 e
2 n
3 g
4 u
5 i
6 n 

Nested for Loops

If you think a simple for loop is easy, nested for loops can be a bit difficult to wrap your head around. Below, the inner loop repeats 4 times inside another loop, which itself repeats 4 times:
>>> for i in 'abcd': 
        for j in 'abcd': 
            print i, j  
        print ''	
a a
a b
a c
a d

b a
b b
b c
b d

c a
c b
c c
c d

d a
d b
d c
d d
Why stop at two? Try a 3-level for loop from Anne Dawson's page. Search for "nested for loop".