[Tutor] list comprehension equivalent to map(function, list item)

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Dec 14 03:20:44 CET 2013


On 14/12/2013 01:03, Bo Morris wrote:
> i have the following simple function that iterates over the list. It
> passes the list item into the function and adds the numbers. What would
> be the equivalent way of writing the "map" portion with list
> comprehension? My code is as follows:
>
> def add(number):
>      print 1 + int(number)
>
> x = ['2', '4', '6', '8', '10', '12']
>
> map(add, x)
>
> thanks for the help and thank you for this mailing list.
>
> AngryNinja
>

I don't see any function that iterates over anything.  I do see a 
function that takes something called number (IMHO a very poor name), 
converts it into an int, adds 1 to it, prints it out and then returns 
None, the default when no return statement is given in a function.  So 
change print to return, add it all up (very loud groan :) and you have.

def add(number):
     return 1 + int(number)

y = [add(z) for z in x]

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list