Python: call a function with more arguments on each element of a list

Last updated on Fri, 2008-06-27 18:12. Originally submitted by fabio on 2008-06-25 12:13.

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.

Posted in:

what about partial from

Submitted by Anonymous (not verified) on Wed, 2010-10-20 17:05.

what about partial from functools?

Great help! Thanks for the

Submitted by Ravi (not verified) on Fri, 2010-01-08 12:56.

Great help! Thanks for the tips.

Thank You

Submitted by Anonymous (not verified) on Fri, 2009-11-06 16:12.

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

Submitted by Alper (not verified) on Fri, 2008-08-01 20:57.

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

The content of this field is kept private and will not be shown publicly.
If you have a personal or company website insert its address in the form http://www.example.com/ .
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <del> <img> <h2> <h3> <h4> <b> <video> <sub> <sup>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You may use [inline:xx] tags to display uploaded files or images inline.
  • You may insert videos with [video:URL]
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.

More information about formatting options