Simple list.append() question
Bernhard Herzog
herzog at online.de
Tue Apr 25 13:29:42 EDT 2000
m.faassen at vet.uu.nl (Martijn Faassen) writes:
> Generally it's a good idea to avoid * on sequences, unless that sequence is
> immutable and contains immutable things; i.e. strings.
It seems to me that the important criterion is whether the elements are
immutable. The mutability of the sequence itself doesn't really matter
here.
> Is there any useful way to use * on lists that I missed?
Something like [None] * 1000 is very useful IMO.
> Usually we want the copy semantics here, not the reference semantics.
If the elements are mutable. But then the question is how deeply do you
copy them?
> Perhaps it's a good idea to completely forbid * on lists in p3k?
> Tuples too for all I care. Then again I may be missing important uses,
> so enlighten me.
AFAICT, I use * with lists most often to create a new list of n
identical immutable elements, most often None or '' or somesuch and I
find that really useful.
What seems to cause the most problems is that newbies try to use it to
create empty multi-dimensional arrays and that fails. I think they try
it because they see it more as a declaration similar to C's
'int[10][20]' than an expression. It would be a good idea IMO to find a
good syntax for this case and ISTM that list comprehensions might be
useful here:
multi_list = [[] for i in range(10)]
or whatever the precise syntax was. Hmm, the unused variable in there is
a bit ugly though.
--
Bernhard Herzog | Sketch, a drawing program for Unix
herzog at online.de | http://sketch.sourceforge.net/
More information about the Python-list
mailing list