Search code examples
pythontupleslist-comprehensiongeneratoriterable-unpacking

Why does comprehension only work with tuples when unpacking in Python?


I tried to use list comprehension on a tuple and it worked fine when unpacking, but not when assigning to a single variable.

If I run the following code

var1, var2, var3 = (i for i in range(3))

var1 = 1, var2 = 2, and var3 = 3 as expected. However, when running the following

varTuple = (i for i in range(3))

varTuple = <generator object <genexpr> at [MEMORY ADDRESS]>, instead of the expected (1, 2, 3)


Solution

  • You've created a generator expression rather than a list (or set or dictionary) comprehension.

    In the first case you're unpacking that generator, so it generates the three values. In the second case you're not, so no values have been generated. You just see the generator object itself.

    You may wish to explicitly convert to a tuple.

    >>> v = (i for i in range(3))
    >>> v
    <generator object <genexpr> at 0x102837c40>
    >>> tuple(v)
    (0, 1, 2)
    

    Note that once the generator has been consumed, it cannot be used again.

    >>> v = (i for i in range(3))
    >>> tuple(v)
    (0, 1, 2)
    >>> tuple(v)
    ()