I am new to python. I have a few questions coming from an armature!
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Aug 16 02:59:46 EDT 2016
On Tuesday 16 August 2016 16:28, Lawrence D’Oliveiro 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.
>
> Why could this difference be important?
*shrug*
Some members of the Python community, particularly GvR, prefer list
comprehensions and generator expressions to using the Lisp-ish "map()"
function.
At least in the past, and possibly still, using a comprehension or a generator
expression may be more efficient, as it can avoid the expense of a function
call. The advice that used to be given (and which may still be valid, for all I
know) is that if you have to write a function using lambda in order to use
map(), it's usually faster to use a comprehension/genexp.
E.g. out of the following:
[len(x)+1 for x in sequence]
list(map(lambda x: len(x) + 1, sequence))
the first will probably be faster as well as easier to read and write.
--
Steve
More information about the Python-list
mailing list