Search code examples
pythondictionaryternary

What’s wrong with my ternary expression or mapping in Python?


I need to retrieve a list (lets call it list1) of the double of every element smaller than 5 and put them in another list (let’s call it list2). I tried to use map as below but for some reason I get invalid syntax:

list2 = map(lambda x: x*2 if x < 5, list1)

I suspect it’s because the ternary expression needs an else condition. Is that it? And what should I do about it?


Solution

  • You’re right about the ternary expression part. Python doesn't allow you to use the syntax: var = <action> if <condition> without else because, in the case where <condition> == False, var becomes unknown.

    You don’t really need map, however, you could use list comprehensions because not only do they solve your problems, they’re more efficient than mapping:

    list2 = [x*2 for x in list1 if x < 5]