The for loop
The previous article in this series, "Discover Python, Part 5: Programming in Python," discussed the
if statement and the
while loop, which required discussing compound statements and the appropriate indentation of Python statements to indicate blocks of related Python code. The end of that article introduced the Python
for loop. But given its utility and power, the
for loop deserves more attention, so it's the sole focus of this article.
for loop fundamentally has a simple syntax, allowing you to extract a single item from a container object and do something with it. Simply put, the
for loop lets you iterate through the items in a collection of objects. The collection of objects can be any Python container type, including the
list types discussed in earlier articles. The container metaphor is more powerful than might be indicated by just these three types, however. This metaphor includes other sequence types, such as
set, which will be discussed in future articles.
But wait! There's more: The
for loop can be utilized to iterate over any object that supports the iteration metaphor, which makes the
for loop very powerful.
The basic syntax of a
for loop is shown in Listing 1, which also demonstrates how to use
break statements within a
Listing 1. Pseudocode for the
for item in container: if conditionA: # Skip this item continue elif conditionB: # Done with loop break # action to repeat for each item in the container else: # action to take once we have finished the loop.
The second article in this series, "Discover Python, Part 2: Explore the Python type hierarchy," introduced the Python
tuple. As discussed, the
tuple type is an immutable heterogeneous container. This basically means that a
tuple can hold different types of objects, but once it's created, it can't be changed. Listing 2 demonstrates how to use a
for loop to iterate through the elements of a
Listing 2. The
for loop and a
>>> t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) >>> count = 0 >>> for num in t: ... count += num ... else: ... print count ... 45 >>> count = 0 >>> for num in t: ... if num % 2: ... continue ... count += num ... else: ... print count ... 20
This example first creates a
t that holds the integers 0 to 9, inclusive. The first
for loop iterates through this
tuple, cumulating the sum of the numbers in the
tuple in the
count variable. Once the code has iterated over all the elements in the
tuple, it enters the
else clause of the
for loop, which prints out the value of the
for loop shown in Listing 2 also iterates over all elements in the
tuple. In this case, however, it only cumulates the values of those items in the container that are evenly divisible by 2 (remember that the
if statement evaluates true if the expression is nonzero, which happens with the
% operator when
num isn't evenly divisible by 2). This restriction is accomplished by using an appropriate
if statement with a
continue statement. As discussed in the previous article, the
continue statement causes the containing loop to start the next iteration. An alternative method to accomplish the same result would test whether the current item in the
tuple is even (using
if not num % 2:) and, if true, would add the current item to the running total. Once the code finishes iterating through the
else clause is invoked, and the running total is printed.
The third article in this series, "Discover Python, Part 3: Explore the Python type hierarchy," discussed the Python
string is an immutable homogeneous container, which means it can only hold characters and can't be modified once it has been created. Listing 3 demonstrates how to use a Python
string as the container for a
Listing 3. The
for loop and a
>>> st = "Python Is A Great Programming Language!" >>> for c in st: ... print c, ... P y t h o n I s A G r e a t P r o g r a m m i n g L a n g u a g e ! >>> count = 0 >>> for c in st: ... if c in "aeiou": ... count += 1 ... else: ... print count ... 10 >>> count = 0 >>> for c in st.lower(): ... if c in "aeiou": ... count += 1 ... else: ... print count ... 12
This example provides three different
for loops that all iterate over the same
string. The first
for loop iterates over the
string "Python Is A Great Programming Language!" and prints each character in the
string one at a time. In this case, the
c. This makes the
The next two
for loops iterate through the string and count how many vowels ('a', 'e', 'i', 'o', or 'u') it contains. The second
for loop only finds lowercase vowels as it iterates over the original
string. The third
for loop, however, iterates over a temporary
string returned by a call to the
lower method. The
lower method converts all the characters in the calling
string to lowercase. Thus, the third
for loop finds two additional vowels.
The fourth article in this series, "Discover Python, Part 4: Explore the Python type hierarchy," introduced the Python
list is a heterogeneous mutable container, which means it can hold different types of objects and can be modified after it has been created. Listing 4 demonstrates how to use a
list with a
Listing 4. The
for loop and a
>>> mylist = [1, 1.0, 1.0j, '1', (1,), ] >>> for item in mylist: ... print item, "\t", type(item)) ... 1 <type 'int'> 1.0 <type 'float'> 1j <type 'complex'> 1 <type 'str'> (1,) <type 'tuple'>  <type 'list'>
Given that the
list is the workhorse of the Python container types (as you'll see many times throughout the rest of the articles in this series), this example may seem overly simplistic. However, that is part of the point: Using a
for loop makes working with each item in a container simple, even with a
list that contains a variety of different objects. This example iterates over all the items in a Python
list and prints each item and its corresponding Python type on a separate line.
Iteration and mutable containers
list is a mutable sequence, which creates an intriguing possibility: that the body of the
for loop could modify the
list it is being iterated over. As you might expect, this is not a good thing, and the Python interpreter won't behave nicely if you try to do it, as shown in Listing 5.
Listing 5. Modifying container within a
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for item in mylist: ... if item % 2: ... mylist.insert(0, 100) ... ^CTraceback (most recent call last): File "<stdin>", line 3, in ? KeyboardInterrupt >>> print mylist [100, ...., 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Many lines deleted for clarity >>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for item in mylist[:]: ... if item % 2: ... mylist.insert(0, 100) ... >>> print mylist [100, 100, 100, 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for loop in this example tries to insert the number 100 at the start of the
list whenever it finds an odd number in the original
list. Granted, this is an unusual way to demonstrate this problem, but it does so very nicely. Once you press Enter following the last three-dot Python prompt, the Python interpreter starts churning away in an infinite loop. To stop the insanity, you must interrupt the process by pressing Ctrl-C (which appears as
^C in the Python output), which is followed by a
KeyboardInterrupt exception. If you print out the modified
list, you'll see that
mylist now contains a very large number of elements with the value 100 (the exact number of new elements depends on how quickly you interrupted the loop).
for loop in this example demonstrates how to avoid this problem. You create a copy of the original
list using the slice operator. The
for loop now iterates through the copy, while you're modifying the original
list. The end result is a modified original
list that now starts with five new elements of 100.
The for loop and sequence indexing
for loop may seem odd if you've ever used another programming language. You may think it more closely resembles a
foreach loop. C-based programming languages have a
for loop, but it's designed to perform a series of operations a specific number of times. The Python
for loop can mimic this behavior by using the built-in
xrange methods. These two methods are demonstrated in Listing 6.
Listing 6. The
>>> r = range(10) >>> print r [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> type(r) <type 'list'> >>> xr = xrange(10) >>> print xr xrange(10) >>> type(xr) <type 'xrange'>
This example first demonstrates the
range method, which creates a new
list that contains a series of integers. The general form for calling the
range method is to supply a single value, used as the upper limit for the
list of integers. Zero is the initial value. Hence, the call
range(10) creates a
list containing the integers 0 through 9, inclusive. The
range method accepts a starting index, as well as a step size. So, the call
range(11,20) creates a
list of integers from 11 to 19, inclusive, whereas the call
range(12, 89, 2) creates a
list of the even integers from 12 to 88.
xrange method behaves much like the
range method in that it creates a
list of integers (and takes the same arguments). However, the
xrange method creates the integers in the
list only as they're needed. For example, in Listing 6, attempting to print out the newly created
xrange didn't show anything other than the name of the
xrange method is preferred when you need to iterate over a large number of integers because it won't create the full
list, which could consume a large quantity of your computer's memory.
Listing 7 demonstrate how you can use the
range method within a
for loop to create a times table for the integers 1 through 10, inclusive.
Listing 7. Making a times table
>>> for row in range(1, 11): ... for col in range(1, 11): ... print "%3d " % (row * col), ... print ... 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
This example uses two
for loops. The outer
for loop takes care of each row in the times table, and the nested
for loop takes care of the columns within each row. Each loop iterates over a
list that contains the integers 1 to 10, inclusive. The innermost
string composed of different data types in a nicely formatted layout. The full details aren't important right now and will be covered in a future article (they will be familiar to anyone with knowledge of the C programming language's
printf method). In this example, the string formatting specifies that a new
string will be created from an integer and that three characters need to be reserved to hold the integer (if the integer is fewer than three characters, it will be left-padded with spaces, which makes things line up). The second
range method can also be used to iterate over a container, accessing each item in the sequence by using the appropriate index. To do this, you need a
list of integers that encompasses the allowed range of index values for the container, which can be easily done by using the
range method with the
len method, as shown in Listing 8.
Listing 8. Indexing a container within a
>>> st = "Python Is A Great Programming Language!" >>> for index in range(len(st)): ... print st[index], ... P y t h o n I s A G r e a t P r o g r a m m i n g L a n g u a g e ! >>> for item in st.split(' '): ... print item, len(item) ... Python 6 Is 2 A 1 Great 5 Programming 11 Language! 9
This final example demonstrates how to use the
len method as the argument to the
range method to create a
list of integers that can be used to access each character from the
string individually. The second
for loop also shows how to split a
string into a
list of substrings (using the space character to indicate the boundaries of substrings). The
for loop iterates over the
list of substrings, printing out each substring and its length.
This article has discussed the Python
for loop and demonstrated some of its many uses. You can use the
for loop with any Python object that provides an iterator, including the built-in sequence types such as the
list. Together, the
for loop and the
list sequence make a powerful team you'll find yourself using over and over in a wide range of circumstances. Python provides a simple mechanism for combining these two concepts, called List Comprehensions, which will be covered in a future article.
"Discover Python, Part 2" discusses the Python type hierarchy and provides a discussion of the Python
"Discover Python, Part 3" provides a detailed discussion of the Python
"Discover Python, Part 4" introduces the Python
listand demonstrates how to use it within a Python program.
And " Discover Python, Part 5" introduces the concept of compound statements in Python, and the
ifstatement and the
- When you have a working Python interpreter, the Python tutorial is a great place to start learning the language.
- Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.
Get products and technologies
- Download Python from the Python Web site.
- Innovate your next open source development project with IBM trial software, available for download or on DVD.
- Get involved in the developerWorks community by participating in developerWorks blogs.