Many newbie questions regarding python

Andreas Waldenburger usenot at geekmail.INVALID
Fri Oct 8 15:22:30 EDT 2010


On Thu, 7 Oct 2010 18:34:58 -0700 (PDT) alex23 <wuwei23 at gmail.com>
wrote:

> 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.

The "correct" solution is the one that works the way you want it to
work (that's my definition, anyway). There is nothing "lucky" about
building a list via [value]*count. It repeats (but not so much
duplicates!) "value" "count" times. It is well defined (and, I think,
justified) behavior.

It ceases to be as useful when mutable types are involved, but so what?
Use something else, then.

And I think it is not too much to ask of a reader of Python to know
that integers are immutable. There are enough pitfalls that make this
knowledge rather important to have. (I'm actually not convinced that
this works as an argument, but there you go.)

TL;DR: Don't say "correct", say "appropriate".

/W

-- 
To reach me via email, replace INVALID with the country code of my home 
country.  But if you spam me, I'll be one sour Kraut.




More information about the Python-list mailing list