Python iteration usage example tutorial

  • 2020-04-02 14:06:26
  • OfStack

This example demonstrates the use of iteration in Python and is a very useful technique. Share with you for your reference. Specific analysis is as follows:

If we are given a list or tuple, we can iterate over the list or tuple through a for loop, which we call Iteration.

In Python, iteration is done through a for... In, while in many languages, such as C or Java, iterating the list is done by subscripts, such as Java code:


for (i=0; i<list.length; i++) {
  n = list[i];
}

As you can see, Python's for loop is more abstract than Java's for loop, because Python's for loop can be used not only on a list or tuple, but also on other iterable objects.

Although list has subscripts, many other data types do not have subscripts. However, as long as it is an iterable object, it can iterate with or without subscripts. For example, dict can iterate:


>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...   print key
...
a
c
b

Because dict's storage is not ordered in the order of a list, the order of the results of the iteration is likely to be different.

By default, dict iterates over the key. If you want to iterate over value, you can use for value in d.tervalues (); if you want to iterate over both key and value, you can use for k, v in d.teritems ().

Since strings are also iterable objects, they can also be applied to the for loop:


>>> for ch in 'ABC':
...   print ch
...
A
B
C

So, when we use a for loop, the for loop works as long as it ACTS on an iterable object, and we don't care much whether the object is a list or some other data type.

So, how do you determine if an object is an iterable object? The method is determined by the Iterable type of the collections module:


>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str iterability 
True
>>> isinstance([1,2,3], Iterable) # list iterability 
True
>>> isinstance(123, Iterable) #  Whether integers are iterable 
False

Finally, what if I want to implement a java-like subscript loop on a list? Python's built-in enumerate function can turn a list into an index-element pair, so it can iterate over both the index and the element itself in the for loop:


>>> for i, value in enumerate(['A', 'B', 'C']):
...   print i, value
...
0 A
1 B
2 C

In the for loop above, both variables are referenced, which is common in Python, such as the following code:


>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...   print x, y
...
1 1
2 4
3 9

Summary:

Any iterable object can act on the for loop, including our custom data types, and as long as the iteration conditions are met, the for loop can be used.

Hopefully, the example of iteration described in this article has helped you learn about Python programming.


Related articles: