0

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)

1
  • important to understand, there are no tuples involved in your code Commented Jun 5, 2024 at 23:40

1 Answer 1

1

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) () 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.