This article mainly introduces the use of the for loop in Python, from the technical documentation on the IBM official website. for more information, see
For loop
The article "explore Python, Part 1: Program with Python" in the previous sections of this series discusses if statements and while loops, composite statements, and the appropriate indentation of Python statements to indicate the relevant Python code blocks. The end of this article introduces the Python for loop. However, in terms of its usage and functions, the for loop is worth noting. Therefore, this article separately describes this loop.
A for loop has a simple syntax that allows you to extract a single project from a container object and perform some operations on it. To put it simply, you can use a for loop to iterate the items in the object set. The object set can be any Python container type, including the tuple, string, and list types discussed in the previous article. However, container metaphor is more powerful than the three types. Metaphor includes other sequence types, such as dictionary and set. they will be discussed in future articles.
But please wait! More information: the for loop can be used to iterate any object that supports iteration of metaphor, which makes the for loop very useful.
Listing 1 shows the basic syntax of the for loop and shows how to use the continue and break statements in the for loop.
Listing 1. pseudo code of 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, "explore Python, Part 1: Explore Python-type hierarchies", introduces Python tuple. As described in this article, the tuple type is an unchangeable heterogeneous container. This mainly means that tuple can store different types of objects, but once it is created, it cannot be changed. Listing 2 demonstrates how to use the for loop to iterate the tuple element.
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
In this example, a tuple named t is created to store integers 0 to 9 (including 9 ). The first for loop iterates this tuple and accumulates the sum of values in the tuple in the count variable. Once the code has iterated all the elements in the 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 all elements in the tuple. However, it only accumulates the values of the items that can be divisible by 2 in the container (remember that if the expression is non-zero, the if statement is true, when num cannot be divisible by 2, the % operator returns a non-zero value ). This restriction is achieved by using the appropriate if statement and continue statement. As described in the previous article, the continue statement starts the next iteration of the loop containing it. Another way to achieve the same result is to test whether the current item in tuple is an even number (if not num % 2 :). if it is true, add the current item to the total running number. Once the code completes the iteration in tuple, the else clause is called to print the sum.
The third article in this series, "exploring Python: Part 1: Exploring Python-type hierarchies", discusses Python string. String is an unchangeable homogeneous container, which means it can only store characters and cannot be modified once it is created. Listing 3 demonstrates how to use a Python string as a container for a 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 on the same string. The first for loop iteration string "Python Is A Great Programming Language !" Print a character in the string at a time. In this example, a comma is added after the print statement variable c. This enables the print statement to print character values followed by space characters, rather than line breaks. If no comma is followed, all characters are printed in separate rows, which is hard to read.
The next two for loops iterate over the string and calculate the number of vowels ("a", "e", "I", "o", or "u") it contains "). The second for loop searches for only lower-case vowels when iterating the original string. The third for loop iteration calls the temporary string returned by the lower method of the string object. The lower method converts all characters in string to lowercase. Therefore, the third for loop can find the other two vowels.
The fourth article in this series, "explore Python, Part 1: Explore Python hierarchies", introduces Python list. List is a heterogeneous variable container, which means it can store different types of objects and be modified after creation. Listing 4 demonstrates 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
1.0
1j
1
(1,)
[1]
Since list is a flexible Python container type (you will see it multiple times in other articles in this series), this example may seem too simple. However, this is part of the main point: using a for loop makes it very easy to process every project in the container, even to process a list containing various objects. In this example, all the items in the Python list are iterated, and each item and its corresponding Python type are printed in a separate row.
Iteration and variable container
Python list is a variable sequence that provides a curious possibility: the for loop subject can modify its list that is being iterated. As you may think, this is not good. if you perform this operation, the Python interpreter will not work 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 "
", 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]
In this example, if an odd number is found in the original list, the first for loop inserts a value of 100 at the beginning of the list. Of course, this is an unusual way to demonstrate this problem, but it is very good. Once the three-point Python prompt is followed by the Enter key, the Python interpreter is in the chaos of infinite loops. To stop this confusion, you must press Ctrl-C (which is displayed as ^ C in the Python output) to interrupt the process, and then a KeyboardInterrupt exception occurs. 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 the speed at which you interrupt 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. Now the for loop iterates the copy and modifies the original list. The final result is the modified original list, which starts with five new elements with a value of 100.
For loop and sequential index
If you have used other programming languages, the Python for loop may look a bit odd. You may think it is more like a foreach loop. The C-based programming language has a for loop, but it is designed to execute a specific number of operations. Python for loops can be simulated by using the built-in range and xrange methods. The two methods are demonstrated in listing 6.
Listing 6. range and xrange methods
>>> r = range(10)>>> print r[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> type(r)
>>> xr = xrange(10)>>> print xrxrange(10)>>> type(xr)
This example first demonstrates the range method, which creates a new list containing a series of integers. Generally, a single value is provided to call the range method, which is used as the upper limit of the integer list. Zero is the starting value. Therefore, calling range (10) will create a list containing integers 0 to 9 (including 9. The range method accepts the Start Index and step size. Therefore, calling range () will create an integer list from 11 to 19 (including 19), while calling range (12, 89, 2) creates an even list from 12 to 88.
Because the xrange method also creates an integer list (which uses the same parameters), it is very similar to the range method. However, the xrange method creates an integer in the list only when necessary. For example, when listing 6 tries to print the newly created xrange, no data is displayed except the xrange name. When a large number of integers need to be iterated, the xrange method is more suitable because it does not create a large list, which consumes a lot of computer memory.
Listing 7 demonstrates how to use the range method in a for loop to create a multiplication table ranging from 1 to 10 (including 10.
Listing 7. Creating a multiplication 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
In this example, two for loops are used. the for loop outside focuses on each row in the multiplication table, and the nested for loop focuses on the columns in each row. Each loop iterates the list containing integers 1 to 10 (including 10. The print statement uses a new concept named string formatting to create a table with exquisite format settings. String formatting is a very useful technique. it is used to create a string composed of different data types in a beautifully formatted layout. The current details are not important, and will be described in future articles (anyone familiar with the printf method of C programming language will be familiar with this content ). In this example, string formatting specifies that a new string will be created from the integer and three characters must be retained to store the integer (if the integer is less than three characters, it will be filled with spaces on the left, so that the data is arranged neatly ). The second print statement is used to print a new row, so that the next row in the multiplication table is printed in the new row.
The range method can also be used for iteration containers to access each item in a sequence by using an appropriate index. To perform this operation, you need to include an integer list of permitted range index values of the container, which can be easily implemented by using the range method and len method, as shown in listing 8.
Listing 8. indexing containers in a 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 6Is 2A 1Great 5Programming 11Language! 9
The final example demonstrates how to use the len method as the parameter of the range method and create an integer list that can be used to separately access each character in the string. The second for loop also shows how to split a string into a list of substrings (using space characters to indicate the boundary of the substrings ). For loop iteration sub-string list, print each sub-string and its length.
Conclusion
This article discusses the Python for loop and demonstrates some of its usage methods. You can use a for loop with any Python object that provides the iterator. these objects include built-in sequence types such as tuple, string, and list. When a for loop is used with a list sequence, you can use them in many cases. Python provides a simple mechanism for combining these two concepts, called list comprehension, which will be described in future articles.