Take the 2-minute tour ×

anyone have any idea how to unpack the values in a tuple for a list comprehension?

So a practical example:

def func(x,y):
    return x*2, y*2

x = [1, 2, 3]; y = [1, 2, 3]

a, b = [ func(i,j) for i, j in zip(x,y) ] 

Unfortunately, that gives me an error sayin' there are too many values to unpack...

I've tried

(a,b) = ...
share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

Do you mean the following?:

a, b = zip(*[func(i,j) for i, j in zip(x,y)])
share|improve this answer
that's exactly what i mean. thanks. –  takrliu Feb 22 '11 at 22:40
add comment
for x1,y1 in [func(i,j) for i, j in zip(x,y)]:
     # do something with x1,y1
share|improve this answer
add comment

The problem is that the list comprehension returns something like

[(1,1), (4,4), (6,6),..]

so the list contains more than just two elements.

I don't see why you can't just do:

a = [i*2 for i in x]
b = [i*2 for i in y]

If you are worried about duplicate code, create a function:

def func(l):
    return [i*2 for i in l]

a, b = func(x), func(y)

Trying to pack everything in one line, using fancy list unpacking etc., does not necessarily increase readability.

share|improve this answer
Sometimes; you write something definite and you never want to write it again, this is one of those things. Like a regex expression, just crank it out hard one night and get it over with. –  takrliu Feb 22 '11 at 22:42
add comment

Your Answer


