Search code examples
pythonpython-3.xlistlist-comprehension

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)

Solution

  • 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.