0

I would like using an if condition in a generator object, but get a syntax error. Please, any idea?

list_a = list(range(1,5))
list_b = [True, True, False, True]

my_zip = list(zip(list_a, list_b))
new = [2*l[0] if l[1] for l in my_zip]

    new = [2*l[0] if l[1] for l in my_zip]
                        ^
SyntaxError: invalid syntax

Any feedbacks are welcomed! Thanks!

pierre_j
  • 895
  • 2
  • 11
  • 26
  • If you want to use a *filter* then you need to do it after the `for` clause, i.e `[2*a for a,b in my_zip if b]` – juanpa.arrivillaga Mar 21 '20 at 22:29
  • 2
    Note, there are no generators here. This is a *list comprehension*. As an aside, stop adding `list` everywhere. It is completely pointless for `list(range(1,5))` and defeats the purpose of creating a lazy zip-iterator in `list(zip(list_a, list_b))` – juanpa.arrivillaga Mar 21 '20 at 22:30
  • Hello @juanpa.arrivillaga, thanks for your feedbacks. Yes you are right. As the zip-iterator gets exhausted after a 1st use, and I was making some print() to try to understand what was going on, I ended up using **list**. thanks again! – pierre_j Mar 22 '20 at 16:40

1 Answers1

2

Perhaps you meant:

new = [2*l[0] for l in my_zip if l[1]]
quamrana
  • 37,849
  • 12
  • 53
  • 71