Many newbie questions regarding python

alex23 wuwei23 at gmail.com
Fri Oct 8 03:34:58 CEST 2010


On Oct 8, 10:27 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> >     v = [0 for i in range(20)]
>
> Absolutely not. Such a code snippet is very common, in fact I've done it
> myself, but it is a "hammer solution" -- to a small boy with a hammer,
> everything looks like a nail that needs hammering. Writing such a list
> comprehension is a "list comp solution".
>
> >     v = [0] * 20
>
> Yes, this is the solution.

But the list comp version will work as expected for mutable types,
whereas the 'solution' only works for immutable types.

If anything, I feel like the list comp version is the correct solution
because of its reliability, whereas the multiplication form feels like
either a lucky naive approach or relies on the reader to know the type
of the initialising value and its mutability.



More information about the Python-list mailing list