If a list or tuple is given, we can iterate through it using a for loop. This kind of traversal is called Iteration.
In Python, iteration is accomplished using for ... in. In many other languages, such as C, iterating over a list is done using subscripts (indices). For example, here’s C code:
for (i = 0; i < length; i++) {
n = list[i];
}
As you can see, Python’s for loop is at a higher level of abstraction than C’s for loop. This is because Python’s for loop can be used not only on lists or tuples but also on any other iterable object.
Although the list data type has indices, many other data types do not. However, as long as an object is iterable, it can be iterated over regardless of whether it has indices or not. For example, a dict can be iterated over:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
c
b
Because a dict is not stored in the sequential manner of a list, the order of the iterated results is likely to be different.
By default, when iterating over a dict, you are iterating over its keys. If you want to iterate over the values, you can use for value in d.values(). If you want to iterate over both keys and values simultaneously, you can use for k, v in d.items().
Since strings are also iterable objects, they can also be used in for loops:
>>> for ch in 'ABC':
... print(ch)
...
A
B
C
Therefore, when we use a for loop, it will work correctly as long as it acts on an iterable object. We don’t need to be overly concerned with whether the object is a list or another data type.
So, how do we determine if an object is iterable? The method is to check against the Iterable type from the collections.abc module:
>>> from collections.abc import Iterable
>>> isinstance('abc', Iterable) # Is str iterable?
True
>>> isinstance([1, 2, 3], Iterable) # Is list iterable?
True
>>> isinstance(123, Iterable) # Is integer iterable?
False
Finally, a small question: what if we want to implement a subscript-based loop for a list, similar to Java? Python’s built-in enumerate function can turn a list into a sequence of index-element pairs. This allows us to iterate over both the index and the element itself simultaneously in a for loop:
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
In the for loop above, we reference two variables simultaneously. This is a very common idiom in Python, as seen in the following code:
>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9
Any iterable object can be used in a for loop, including custom data types we define. As long as they meet the criteria for being iterable, they can be used with a for loop.