Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unpacking from list comprehension over empty input

Tags:

python

When working with a function that returns multiple values with a tuple, I will often find myself using the following idiom to unpack the results from inside a list comprehension.

fiz, buz = zip(*[f(x) for x in input])

Most of the time this works fine, but it throws a ValueError: need more than 0 values to unpack if input is empty. The two ways I can think of to get around this are

fiz = []
buz = []
for x in input:
    a, b = f(x)
    fiz.append(a)
    buz.append(b)

and

if input:
    fiz, buz = zip(*[f(x) for x in input])
else:
    fiz, buz = [], []

but neither of these feels especially Pythonic—the former is overly verbose and the latter doesn't work if input is a generator rather than a list (in addition to requiring an if/else where I feel like one really shouldn't be needed).

Is there a good simple way to do this? I've mostly been working in Python 2.7 recently, but would also be interested in knowing any Python 3 solutions if they are different.

like image 578
Nyle Avatar asked Feb 20 '26 20:02

Nyle


1 Answers

If f = lambda x: (x,x**2) then this works

x,y = zip(*map(f,input)) if len(input) else ((),())

If input=[], x=() and y=().

If input=[2], x=(2,) and y=(4,)

If input=[2,3], x=(2,3) and y=(4,9)

They're tuples (not lists), but thats thats pretty easy to change.

like image 104
woodpav Avatar answered Feb 23 '26 10:02

woodpav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!