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

spir denis.spir at gmail.com
Sat Dec 14 15:12:15 CET 2013


On 12/14/2013 10:12 AM, 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.

Have you tried your own code? If I add one print() for each result and run the 
code, here is the output by me:

3
5
7
9
11
13
[None, None, None, None, None, None]
<map object at 0x7fa4fb7fd550>

Certainly these are not "the same results". And probably neither of them is the 
result you expected. I guess you go on using very imprecise, in fact wrong, 
terminology, and this drives you into thinking wrongly.

There also are worng terms in your code itself, already signaled bu other (but 
you did not correct or even take into account, apparently), and consequent 
errors of thinking:
* the "add" function does not "add"
* in fact it does not _produce_ anything (instead it is an action that performs 
an effect, namely writing something onto the terminal) ...
* ...so that using it as loop function in map simply makes no sense: map collect 
the results (products) of a function -- if that function produces results
* this is why we get [None, None...]: a function (the term is wrong, it's 
actually say an "action") that does not produce but performs an effect return 
None by convention in Python.
* "number" is not a number, but hopefully) the written expression of a number, 
whay is technically called a numeral (see wikipedia)

>  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



More information about the Tutor mailing list