-1

I'd like to use a single line expression to create a list of lists with an if condition from three other lists. I use the zip method for this. It's working fine, just not in a single line.

check = [3,2]

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]

# working
my_list = []
for a,b,c in zip(a,b,c):
    if a in check:
        my_list.append( [a,b,c] )

# not working
# my_list = [ [a,b,c] if a in check for a,b,c in zip(a,b,c) ]

print(my_list)

Output

[[2, 6, 10], [3, 7, 11]]

I get "invalid syntax" for "a: list" after the for keyword in the single line expression. Did i miss something?

mtosch
  • 351
  • 4
  • 18

1 Answers1

1

You put the condition in the wrong place. It goes at the end in comprehensions.

my_list = [[a,b,c] for a,b,c in zip(a,b,c) if a in check]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97