-1

The following code does not compile.

data = [5, 3, 2, 4, 1]   

def projector(x):
    if (x % 2) == 0:
        return 1
    else:
        return 0    

# evens = map(projector, data)
evens = map(lambda x: if (x % 2) == 0: 1 else: 0, data)
print(list(evens))

Question

What is the correct lambda that is equivalent to projector above?

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
  • 1
    Does this answer your question? [Is there a way to perform "if" in python's lambda?](https://stackoverflow.com/questions/1585322/is-there-a-way-to-perform-if-in-pythons-lambda) – lunastarwarp Nov 14 '21 at 06:02
  • 1
    In this case you can do `lambda x: (x + 1) % 2` without needing a conditional, but for a general answer see the linked duplicates. – kaya3 Nov 14 '21 at 06:06

1 Answers1

0

See ternary operators

You want:

res = 0 if (x % 2) == 0 else 1

That you can map this way:

evens = map(lambda x: 0 if (x % 2) == 0 else 1, data)