Skip to content
Advertisement

List comprehension returning two variables

I’m trying to do a list comprehension on two lists returning 2 variables in result.

Using for loop:

foo = [1,2,3]
bar = [4,5,6]

for f, b in zip(foo, bar):
    print(f, b)

However, when I try to use list comprehension to do the same execution, it throws a SyntaxError

print(f,b) for f, b in zip(foo, bar)

Advertisement

Answer

You need to have the whole thing in square brackets. Like this:

[print(f, b) for f, b in zip(foo, bar)]

That’s because you are doing the action in the first bit print(f, b) for every elements (f, b) in the tuple you get from the zip function.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement