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

Submitted by fabio on Wed, 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.

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.
  • 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> <img> <h2> <h3> <h4> <b>
  • 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.

More information about formatting options

1 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.