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

Bo Morris crushed26 at gmail.com
Sat Dec 14 10:12:20 CET 2013


Thank you for your assistance. Based on your direction, I figured it out.

*This... *

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

x = ['2', '4', '6', '8', '10', '12']

[add(item) for item in x]

 *Is the same as... *


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

x = ['2', '4', '6', '8', '10', '12']

map(add, x)

They both yield the same results. Is there a benefit to using one way over
the other? In larger computations, does one way calculate faster or is it
merely a preference? Again, thank you.

AngryNinja


On Fri, Dec 13, 2013 at 9:24 PM, Amit Saha <amitsaha.in at gmail.com> wrote:

> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131214/1c4329cf/attachment.html>


More information about the Tutor mailing list