Home > OS >  List comprehension returning two variables
List comprehension returning two variables

Time:10-03

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)

CodePudding user response:

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.

  • Related