On Tue, 20 Sep 2016 15:12:39 +0200, Peter Otten wrote:

> because they don't build lists only to throw them away.

The lists could have been avoided by using iterators, e.g.

import itertools as it
keys = xrange(256)
vals = it.imap(chr, keys)
max(it.imap(operator.setitem, it.repeat(d), keys, vals))

> Also, creating a list of dicts or lists is a common gotcha because after
> 
> outer = [[]] * 3
> 
> the outer list contains *the* *same* list three times, not three empty
> lists.

But in this case, it's not a gotcha; it's intentional that each iteration
operates upon the same dictionary.

Essentially, [d]*len(keys) is a trick to get around the fact that map()
requires all of the arguments (apart from the function) to be sequences.

itertools.repeat() is possibly a better trick, although then you can't use
map(), because map() iterates until *all* sequences are exhausted,
appending None values for shorter sequences. itertools.imap() terminates
once the shortest sequence is exhausted.

In this specific case, a loop or comprehension would have been better. But
in situations where you don't control the iteration, the ability to coerce
something into a pre-determined iteration pattern is useful.

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to