6

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?

AMC
  • 2,642
  • 7
  • 13
  • 35
Rob
  • 3,333
  • 5
  • 28
  • 71

2 Answers2

19
>>> 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']
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 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!!! – Rob Jul 01 '15 at 05:19
  • for future reference... this will not work for `numpy.array` use [`numpy.where`](https://stackoverflow.com/questions/34381847/valueerror-when-trying-to-apply-lambda-expression-to-elements-of-an-array) – Rufus Nov 16 '17 at 02:31
  • So others know for compatibility, this seems to have been added in Python 2.5 with [conditional expressions](https://docs.python.org/2.7/whatsnew/2.5.html#pep-308-conditional-expressions). This isn't available in Python 2.3 that I'm using. –  Jun 13 '18 at 17:54
  • 1
    @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) – John La Rooy Jun 14 '18 at 06:46
  • Is it necessary to have an else clause in the conditional? My code does not work without specifying the else clause. – Ansh Khurana Dec 10 '19 at 09:57
  • 1
    @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]` – John La Rooy Dec 11 '19 at 21:49
2

Ternary operator:

map(lambda x: 'lower' if x<3 else 'higher', lst)
intelis
  • 7,829
  • 14
  • 58
  • 102