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?
To work with map(), the lambda should have one parameter in, representing one element from the source list. Choose a suitable name for the parameter, like n for a list of numbers, s for a list of strings. The result of map() is an "iterable" map object which mostly works like a list, but it does not print.
Using lambda() Function with map()The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.
Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.
You can use the Python map() function with a String. While using the map() with a String, the latter will act like an array. You can then use the map() function as an iterator to iterate through all the string characters.
>>> 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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With