Python: call a function with more arguments on each element of a list
I'm recently working a lot with Python because I understood it perfectly fits my needs being powerful, clean and fast to develop with it.
If you program with it there are good chances that you will end up using lot of lists which are pretty well designed and powerful in Python.
A really useful function in Python is map() which let you execute one function on each element of a list:
L = [0.1, 0.4, 0.7] L2 = map(round, L) print L2 #output [0.0, 0.0, 1.0]
The above code creates a list of floats and using map() rounds them to the nearest integer: we are executing round(element) for each element of the list.
Now, if we want to execute round(element, 1) is not possible to do it using directly map() because we have two parameters for round().
A first solution could be using functional programming features built in Python to create something like:
L = [0.1, 0.4, 0.7] L2 = map(lambda x: round(x, 1), L) print L2 #outputs [0.10000000000000001, 0.40000000000000002, 0.69999999999999996]
Following another solution which you probably would like more:
L = [0.1, 0.4, 0.7] L2 = [round(x, 1) for x in L] print L2 #outputs [0.10000000000000001, 0.40000000000000002, 0.69999999999999996]
Hope this helps someone.



what about partial from
what about partial from functools?
Great help! Thanks for the
Great help! Thanks for the tips.
Thank You
Your lambda function style looked elegant to me and was helpful in my program (and also made me think about lambda as I did not think in that direction) thank you.
Thanks for this quick
Thanks for this quick refresher, I forgot about the map() function from Lisp. Python is looking more like it every day.. :P
Post new comment