Variable Expansion in Python

Python variable expansion is a useful feature. Essentially it allows an iterable to be unpacked into separate variables.

number_tests = [
    ("a", False),
    ("1", True),
    ("1.2", True),
    ("1.3.4", False),
    ("", False),

for testval, expected in number_tests:
    # ...

This is cleaner than accepting the tuple and then unpacking it yourself.

for test_tuple in number_tests:
    test_input = test_tuple[0]
    expected = test_tuple[1]

In fact, when you do inline multi-variable assignments under the hood this is variable expansion.

>>> variable_type = "a", "b"
>>> print(type(variable_type))
<class 'tuple'>
>>> a, b = variable_type
>>> a, b
('a', 'b')

You might have guessed, but the left hand side is also a tuple.

>>> (a, b) = variable_type
>>> a, b
('a', b)
>>> type(_)
<class 'tuple'>

While I’ve known the above rules for years, and enjoyed them frequently when working with comprehensions and iterations, I did not realize you could unpack nested structures in the exact same way. Let’s take a classic example of wanting to enumerate over an iterable, reusing number_tests I used to write:

for idx, test_tuple in enumerate(number_tests):
    testval, expected = test_tuple

But you can further expand by declaring the resulting tuple inline with the for loop:

for idx, (testval, expected) in enumerate(number_tests):
    # Continue on!

This is also completely valid in comprehensions:

>>> [(idx, a, b) for idx, (a, b) in enumerate(number_tests)]
    (0, 'a', False),
    (1, '1', True),
    (2, '1.2', True),
    (3, '1.3.4', False),
    (4, '', False)
written January 21st, 2019

January 2019

Can’t find what you’re looking for? Try hitting the home page or viewing all archives.