[Tutor] list comprehension equivalent to map(function, list item)
Amit Saha
amitsaha.in at gmail.com
Sat Dec 14 03:24:24 CET 2013
On Sat, Dec 14, 2013 at 11:03 AM, Bo Morris <crushed26 at gmail.com> 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)
Think of a list comprehension as:
[ dosomething(item) for item in alist]
And, comparing it with your map implementation, here is what you get:
>>> [1+int(item) for item in x]
[3, 5, 7, 9, 11, 13]
Here, dosomething(item) corresponds to 1+int(item).
Hope that helps.
-Amit.
--
http://echorand.me
More information about the Tutor
mailing list