Michael
Michael

Reputation: 2566

iterable unpacking results in empty object after first iteration

Using the * iterable unpacking operator features I would like to maintain the content of a variable so that I can use the variable at multiple places in my code. Here is a little example expressing what I would like:

>>> a = 1
>>> b = None
>>> c = None
>>> args = (x for x in (a, b, c) if x is not None)
>>> print(*args)
>>> 1
>>> print(*args)
>>> 

The second print returns nothing because args has been unpacked during the first print statement.

Is there a way to maintain the content of a variable by still using the * feature? Obviously, I can delegate (x for x in (a, b, c) if x is not None) into a dedicated function that I will call all the time. I was wondering if there was a simpler / more pythonic way to handle the operation.

Upvotes: 4

Views: 97

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

You need to use [x for x in (a, b, c) if x is not None] (with square brackets) instead of (x for x in (a, b, c) if x is not None).

(...) creates a generator which becomes empty once iterated. Whereas [...] is the syntax of list comprehension which returns the list.

For example:

>>> a = 1
>>> b = None
>>> c = None
>>> args = [x for x in (a, b, c) if x is not None]
>>> print(*args)
1
>>> print(*args)
1

Upvotes: 5

Related Questions