Common Python Idioms


Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code.

x, y = 10, 20

What's happening at a lower level in the above code is:

# Creating a tuple of 10, 20 and then looping over the tuple and taking each of the two items we get from looping and assigning them to x & y.
(x, y) = (10, 20)

If you know the length of a list or tuple, you can assign names to its elements with unpacking.

For example, we can use enumerate() which will provide a tuple of two elements for each item in a list:

for index, item in enumerate(some_list):
    # do something with index and item

You can use this to swap variables too:

a, b = b, a

Nested unpacking:

a, (b, c) = 1, (2, 3)

New introduced way of unpacking:

a, *the_rest = [1, 2, 3]  # a = 1, the_rest = [2, 3]

a, *middle, c = [1, 2, 3, 4]  # a = 1, middle = [2, 3], c = 4
Community content is available under CC-BY-SA unless otherwise noted.