[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code

On Wed, 13 Sep 2017 01:18 am, Paul Moore wrote:

> Using map vs comprehensions is mostly a stylistic choice. Python
> programmers will typically choose a comprehension, so that style looks
> more idiomatic, but the map is not wrong. I haven't tested which is
> faster - I can't imagine it would make much practical difference in a
> real program.

Last time I tested it:

map(f, values)  # Python 2 version of map

[f(x) for x in values]

were equally fast when f was some function, but the comprehension:

[2*x + y for x in values]  # for example

is considerably faster than the map solution using lambda:

map(lambda x: 2*x + y, values)

The lesson is: calling a function isn't free. If you can in-line an expression
rather than call a function to evaluate the expression, you gain.

(Although the more expensive the expression, the less significant the function
call overhead becomes.)

The implication is that the more superfluous function wrappers you have, the
slower your code. If our aim is to have slow, unreadable code, we can take the

map(int, values)

and progressively slow it down:

map(lambda x: int(x), values)

map(lambda y: (lambda x: int(x))(y), values)

map(lambda z: (lambda y: (lambda x: int(x))(y))(z), values)

?Cheer up,? they said, ?things could be worse.? So I cheered up, and sure
enough, things got worse.