Bits of Python Information

zip and zip_longest functions

zip function can be used to process iterators in parallel. In Python 3, zip generator yields tuples containing the next value from each iterator.

However if the lengths of iterators are different, it yields tuples until one of the iterators is exhausted. The zip_longest function from itertools lets you iterate over multiple iterators in parallel regardless of their lengths.

list_a = [1, 2, 3, 4]
list_b = ['one', 'two', 'three', 'four']

for number, name in zip(list_a, list_b):
    print(f'{number}: {name}')

""" Output
1: one
2: two
3: three
4: four
"""

from itertools import zip_longest

# zip_longest can also take a 'fillvalue' parameter
# to fill non matching values.
list_c = ['one', 'two']
for number, name in zip_longest(list_a, list_c, fillvalue='***'):
    print(f'{number}: {name}')

""" Output
1: one
2: two
3: ***
4: ***
"""

Swapping values

In Python, you don't need a temporary variable to swap values. You can do it in one line.

x_val, y_val = y_val, x_val

Running Script in Interactive Mode

Instead of Python exiting when the program is finished, you can use the -i flag to start an interactive session. This can be useful to inspect global variables or a stack trace when a script raises an exception.

python -i your_script.py