Given a list or tuple, we can for
traverse the list or tuple through a loop, which we call iteration.
For example, dict can be iterated:
>>> d = {'a': 1, 'b': 2, 'c': 3} >>> for key in d: ... print(key) ... a c b
Because the storage of dict is not in the order of list, the order of iterated results is likely to be different.
By default, dict iterates over keys. If you want to iterate value, you can use it for value in d.values()
, if you want to iterate key and value at the same time, you can use it for k, v in d.items()
.
Since strings are also iterables, they can also be used in for
loops:
>>> for ch in 'ABC':
... print(ch) ... A B C
So, how to judge an object is an iterable object? The method is judged by the Iterable type of the collections module:
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False
The last little question, what if you want to implement a subscript loop like Java for list? Python has built-in enumerate
functions to turn a list into index-element pairs, so that both the for
index and the element itself can be iterated over in a loop:
>>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C
In the above for
loop, two variables are referenced at the same time, which is very 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