7

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?

2 Answers 2

21
>>> 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']
Sign up to request clarification or add additional context in comments.

6 Comments

ya I figured how to do it with a list comprehension no problem but for some reason kept getting errors when I used if statements in my map. Thanks a lot!!!
for future reference... this will not work for numpy.array use numpy.where
So others know for compatibility, this seems to have been added in Python 2.5 with conditional expressions. This isn't available in Python 2.3 that I'm using.
@JoshDetwiler,open option for Python2.3 is this [('higher', 'lower')[x < 3] for x in lst]. It's harder to read though, and evaluates both options (doesn't really matter here as they are just strings)
@Ansh, it that form it is a ternary - so needs all 3 parts. You can write the condition at the end in the usual way if you wish to filter ['lower' for x in lst if x < 3]
|
2

Ternary operator:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.