[Tutor] list comprehension equivalent to map(function, list item)
Peter Otten
__peter__ at web.de
Sat Dec 14 10:37:06 CET 2013
Bo Morris wrote:
> 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.
For built-in functions map(f, items) is a bit faster. List-comps are more
flexible; you can inline the function
>>> [int(s) + 1 for s in x]
[3, 5, 7, 9, 11, 13]
or add a filter:
>>> [int(s) + 1 for s in x if set("12") & set(s)]
[3, 11, 13]
More information about the Tutor
mailing list