Skip to content

Iteration

When given a list or tuple, we can iterate through it using a for loop, a process known as iteration.

In Python, iteration is accomplished using for ... in, whereas many languages, such as C, perform iteration over a list using indices. For example, in C code:

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

It is clear that Python's for loop has a higher level of abstraction compared to C's for loop, as Python's for loop can be used not only on lists or tuples but also on other iterable objects.

Although the list data type has indices, many other data types do not. However, as long as an object is iterable, whether or not it has indices, it can be iterated over. For example, a dictionary can also be iterated:

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

Since the storage in a dictionary is not ordered like a list, the order of the output may vary.

By default, a dictionary iterates over its keys. To iterate over the values, you can use for value in d.values(), and 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 a for loop:

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

Thus, when we use a for loop, as long as it operates on an iterable object, the for loop will run normally, and we do not need to worry about whether the object is a list or some other data type.

How to Check if an Object is Iterable

So how do we determine if an object is iterable? We can check this using the Iterable type from the collections.abc module:

python
>>> from collections.abc import Iterable
>>> isinstance('abc', Iterable)  # Check if str is iterable
True
>>> isinstance([1, 2, 3], Iterable)  # Check if list is iterable
True
>>> isinstance(123, Iterable)  # Check if integer is iterable
False

Index-based Iteration in Python

One last small issue: how do we implement index-based iteration for a list similar to Java? Python’s built-in enumerate function can convert a list into index-element pairs, allowing us to iterate over both the index and the element itself in a for loop:

python
>>> 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 common in Python. For example, the following code:

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

Exercise

Please use iteration to find the minimum and maximum values in a list and return them as a tuple:

python
def findMinAndMax(L):
    return (None, None)

Test Cases:

python
# Tests
if findMinAndMax([]) != (None, None):
    print('Test failed!')
elif findMinAndMax([7]) != (7, 7):
    print('Test failed!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('Test failed!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('Test failed!')
else:
    print('Test succeeded!')

Summary

Any iterable object can be used in a for loop, including user-defined data types, as long as they meet the conditions for iteration. This allows us to leverage for loops effectively in our programs.

Iteration has loaded