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:

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:
s = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
for i, x in enumerate(s):
print(i, x)
Output:

for-else
Loop
for-else
LoopThe 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.
with open('foo.txt') as file:
for line in file:
stripped = line.strip()
if not stripped:
break
# Do some processing work
else:
print('Processing completed.')
Iterators
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:
# Create an example tuple
>>> example_tuple = ('apple', 'banana', 'cherry')
# Create an iterator using the iter() function
>>> iterator = iter(example_tuple)
# Get next item in the iterator
>>> next(iterator)
'apple'
# Get next item in the iterator
>>> next(iterator)
'banana'
# Get next item in the iterator
>>> next(iterator)
'cherry'
# No more iterm in the iterator
>>> next(iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Last updated
Was this helpful?