Rob
Rob

Reputation: 3459

using a conditional and lambda in map

If I want to take a list of numbers and do something like this:

lst = [1,2,4,5]
[1,2,4,5] ==> ['lower','lower','higher','higher']

where 3 is the condition using the map function, is there an easy way?

Clearly map(lambda x: x<3, lst) gets me pretty close, but how could I include a statement in map that allows me to immediately return a string instead of the booleans?

Upvotes: 6

Views: 27482

Answers (2)

intelis
intelis

Reputation: 8058

Ternary operator:

map(lambda x: 'lower' if x<3 else 'higher', lst)

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304215

>>> lst = [1,2,4,5]
>>> map(lambda x: 'lower' if x < 3 else 'higher', lst)
['lower', 'lower', 'higher', 'higher']

Aside: It's usually preferred to use a list comprehension for this

>>> ['lower' if x < 3 else 'higher' for x in lst]
['lower', 'lower', 'higher', 'higher']

Upvotes: 20

Related Questions