Iteratively unpacking the results into an empty object after the first iteration

Using the functions of the * iterable unpacking operator, I would like to save the contents of the variable so that I can use the variable in several places in my code. Here is a small example in which 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 does not return anything because it argswas unpacked during the first statement print.

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

+4
source share
1 answer

(x for x in (a, b, c) if x is not None) [x for x in (a, b, c) if x is not None] ( ).

(...) , . [...] , .

:

>>> 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
+5

Source: https://habr.com/ru/post/1692093/


All Articles