Detail the use of for loops in Python

  • 2020-05-09 18:48:50
  • OfStack

for cycle

The previous article in this series, "exploring Python, part 5: programming with Python," discussed if statements and while loops, discussed compound statements, and appropriately indented Python statements to indicate the relevant Python code blocks. The article ends with an introduction to the Python for loop. But in terms of usage and functionality, the for loop is more interesting, so this article covers it separately.

The for loop has a simple syntax that allows you to extract a single item from a container object and do something with it. Simply put, using the for loop, you can iterate over the items in the collection of objects. The collection of objects can be any Python container type, including the tuple, string, and list types discussed in the previous articles. But the container metaphor is more powerful than these three types. metaphor includes other sequence types, such as dictionary and set, which will be discussed in future articles.

But wait! More information: the for loop can be used to iterate over any object that supports the iteration of metaphor, which makes the for loop very useful.

The basic syntax for the for loop is shown in listing 1. It also shows how to use the continue and break statements in the for loop.
Listing 1. Pseudocode for the for loop


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, "exploring Python, part 2: exploring the hierarchy of Python types," introduces Python tuple. As described in this article, the tuple type is an immutable heterogeneous container. This basically means that tuple can hold different types of objects, but once it is created, it cannot be changed. Listing 2 demonstrates how to use the for loop to iterate over the tuple elements.
Listing 2. for loop and tuple


>>> 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 starts by creating tuple, called t, which holds the integers 0 through 9 (including 9). The first for loop iterates over this tuple and accumulates the sum of the values in tuple in the count variable. Once the code has iterated through all elements of tuple, it will enter the else clause of the for loop and print the value of the count variable.

The second for loop, shown in listing 2, also iterates through all the elements in tuple. However, it only accumulates the values of the items in the container that are divisible by 2 (remember that if the expression is non-zero, the if statement will be true, and the % operator returns a non-zero value if num is not divisible by 2). This restriction is accomplished by using the appropriate if and continue statements. As described in the previous article, the continue statement causes the loop containing it to start the next iteration. Another way to achieve the same result is to test if the current item in tuple is even (using if not num % 2), and if so, add the current item to the run total. Once the code completes the iteration in tuple, the else clause is invoked and the sum is printed.

The third article in this series, "exploring Python: part 3: exploring the hierarchy of the Python type," discusses Python string. The string is an immutable isomorphic container, which means it can only hold characters and cannot be modified once it is created. Listing 3 shows how to use Python string as the container for the for loop.
Listing 3. for loop and string


>>> 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, all of which iterate over the same 1 string. The first for cycle iteration string "Python Is A Great Programming Language!" Print 1 character in string once. In this example, the print statement variable c is followed by a comma. This causes the print statement to print character values followed by a space character instead of a newline character. Without the trailing comma, the characters are all printed on separate lines, which can be difficult to read.

The next two for loops iterate over the string and calculate how many vowels it contains (" a, "" e," "i," "o," or "u"). The second for loop looks only for lowercase vowels while iterating over the original string. The third for loop iterates over the temporary string returned by calling the lower method of the string object. The lower method converts all characters in string to lowercase. Thus, the third for loop finds the other two vowels.

The fourth article in this series, "exploring Python, part 4: exploring the hierarchy of Python types," introduces Python list. list is a heterogeneous mutable container, which means it can hold different types of objects and can be modified after creation. Listing 4 shows how to use the list and for loops.
Listing 4. for loop and list


>>> mylist = [1, 1.0, 1.0j, '1', (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'>
[1]   <type 'list'>

Since list is a flexible Python container type (which you'll see many times throughout the rest of this series), this example might seem simplistic. However, this is the point of part 1: using the for loop makes it easy to process each item in the container, even list, which contains a variety of different objects. This example iterates through all the items in Python list and prints each item and its corresponding Python type in a separate line.
Iteration and mutable containers

Python list is a mutable sequence that offers a curious possibility: the for loop body can modify the list it is iterating over. As you might think, this is not good, and if you do this, the Python interpreter will not work very well, as shown in listing 5.
Listing 5. Modify the container in the for loop


>>> 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]

The first for loop in this example inserts a value of 100 at the beginning of list whenever an odd number is found in the original list. This is, of course, an unusual way to illustrate the problem, but it's very good. Once you press the Enter key at the three-point Python prompt, the Python interpreter is in an infinite loop of confusion. To stop this mess, you must interrupt the process by pressing Ctrl-C (which is shown as ^C in Python output), and an KeyboardInterrupt exception will appear. If you print out the modified list, you will see that mylist now contains a large number of elements with a value of 100 (the exact number of new elements depends on how quickly you break the loop).

The second for loop in this example demonstrates how to avoid this problem. Use the slice operator to create a copy of the original list. The for loop will now iterate over this replica and modify the original list. The end result is a modified version of the original list, which now starts with five new elements with a value of 100.

for loop and sequence index

If you've worked with other programming languages, the Python for loop might seem a little odd. You might think it's more like the foreach loop. The C-based programming language has an for loop, but it is designed to perform a certain number of operations on series 1. The Python for loop can simulate this behavior by using the built-in range and xrange methods. Both methods are illustrated in listing 6.
Listing 6. The range and xrange methods


>>> 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 containing a series of 1 integers. The 1-like form of calling the range method is to provide a single value that is used as the upper bound of the integer list. Zero is the starting value. Therefore, calling range(10) will create list with the integers 0 through 9 (including 9). The range method accepts the start index and the step size. So, calling range(11,20) will create the integers list from 11 to 19 (including 19), and calling range(12, 89, 2) will create the even Numbers list from 12 to 88.

Because the xrange method also creates the integer list (which USES the same parameter), it is very similar to the range method. However, the xrange method creates an integer in list only when needed. For example, in listing 6, when you try to print the newly created xrange, no data is displayed other than the name of xrange. The xrange method works best when you need to iterate over a large number of integers, because it doesn't create a huge list, which consumes a lot of computer memory.

Listing 7 shows how to use the range method within the for loop to create a multiplication table for the integers 1 through 10 (including 10).
Listing 7. Creating 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 focusing on each row in The Times table, and the nested for loop focusing on the columns in each row. Each loop iterates through list with the integers 1 through 10 (including 10). The innermost print statement USES a new concept called string formatting to create nicely formatted tables. String formatting is a very useful technique for creating string with different data types in a nicely formatted layout. The details are not important now, but will be covered in a future article (they will be familiar to anyone who knows the printf method of the C programming language). In this case, the string formatting specifies that a new string will be created from an integer and that three characters will be reserved to hold the integer (if the integer is less than three characters, Spaces will be filled to the left to align the data). The second print statement is used to print new rows so that the next row in The Times table is printed in the new row.

The range method can also be used to iterate over the container, accessing each item in the sequence by using the appropriate index. To do this, you need the integer list containing the container's allowable range index value, which you can easily do using the range method and the len method, as shown in listing 8.
Listing 8. Indexing the container within the for loop


>>> 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 an argument to the range method to create an integer list that can be used to access each character individually in string. The second for loop also shows how to split string into the list substring (using the space character to indicate the boundaries of the substring). The for loop iterates over the substring list, printing each substring and its length.

conclusion

This article discussed the Python for loop and demonstrated some of its USES. The for loop can be used in conjunction with any Python objects that provide iterators, including built-in sequence types such as tuple, string, and list. The for loop and list sequence 1 are powerful when used, and you'll find yourself using them in many situations. Python provides a simple mechanism for combining these two concepts, called list comprehension, which will be covered in a future article.


Related articles: