Program Structure and Control Flow

Loops and Iterations

Throw-away Variable

The _ symbol is useful when the variable in that position is not important:

s = [(1, 2, 3), (4, 5, 6)]
for x, _, z in s:
    print(x, z)

Wildcard Unpacking

Use *var_name to unpack multiple elements:

s = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
for x, y, *extra in s:
    print(f"{x = }", f"{y = }", f"{extra = }")

Output:

Wildcard Unpacking

Enumerate

Let s be an iterable, then enumerate(s) creates an iterator that produces tuples (0, s[0]), (1, s[1]), (2, s[2]), and so on:

Output:

Enumerate

for-else Loop

The else clause of a loop executes only if the loop runs to completion. This either occurs immediately (if the loop wouldn't execute at all) or after the last iteration. If the loop is terminated early using the break statement, the else clause is skipped.

Iterators

An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for loop.

Lists, tuples, dictionaries, sets, strings, and file objects are all iterable objects. They are iterable containers which you can get an iterator from. All these objects have a iter() method which is used to get an iterator:

Last updated

Was this helpful?