Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading