I am new to python. I have a few questions coming from an armature!

Ian Kelly ian.g.kelly at gmail.com
Tue Aug 16 03:18:44 EDT 2016


On Aug 16, 2016 12:36 AM, "Lawrence D’Oliveiro" <lawrencedo99 at gmail.com>
wrote:

On Tuesday, August 16, 2016 at 6:26:01 PM UTC+12, Paul Rudin wrote:
> sohcahtoa82 writes:
>> squared_plus_one_list = map(lambda x: x**2 + 1, some_list)
>
> I realise that this is about understanding lambda, but it's worth noting
> in passing that we tend to write this sort of thing as:
>
> squared_plus_one_list = [x**2 + 1 for x in some_list]

The difference being that the “map” function takes an iterable and returns
an iterator.


In Python 3, yes. However, assigning the result to the name
"squared_plus_one_list" implies that the author was probably considering
Python 2 code, in which map returns a list, so the comprehension is
equivalent.

Why could this difference be important?


Assigning an iterator to a variable is usually considered un-Pythonic,
because it's easy to accidentally consume the iterator resulting in
difficult-to-diagnose bugs later. If you're immediately iterating over the
result, then sure, use Python 3 map (or a generator expression). If you're
going to reference it later then materializing it (or, if the iteration is
cheap, creating a repeatable iterable) is preferred. Of course, the size of
the list can also be a consideration here.

Also, unless the mapped function is already defined (and preferably
built-in), a generator expression or list comprehension is usually more
readable and avoids the significant overhead of repeatedly calling a Python
function.



More information about the Python-list mailing list