Is there some syntax to unpack a tuple but have an alternate value if one of the values is falsy?
Question:
Example I might have:
x = None
y = x or 0
In a tuple, am I able to somehow unpack the tuple but give some default value if a falsy value is found? Example:
values = (1, None)
one or 0, two or 0 = values
I know that my solution doesn’t work but I was wondering if there is some one-line syntax that does.
Answers:
You could use a generator expression:
one, two = (v or 0 for v in values)
Example I might have:
x = None
y = x or 0
In a tuple, am I able to somehow unpack the tuple but give some default value if a falsy value is found? Example:
values = (1, None)
one or 0, two or 0 = values
I know that my solution doesn’t work but I was wondering if there is some one-line syntax that does.
You could use a generator expression:
one, two = (v or 0 for v in values)