Many newbie questions regarding python
BartC
bc at freeuk.com
Fri Oct 8 08:24:32 EDT 2010
"Rogério Brito" <rbrito at ime.usp.br> wrote in message
news:i8lk0n$g38$1 at speranza.aioe.org...
> My first try to write it in Python was something like this:
>
> v = []
> for i in range(20):
> v[i] = 0
>
> Unfortunately, this doesn't work, as I get an index out of bounds when
> trying to
> index the v list.
Python can't grow a list by assigning to out-of-bound elements (although,
being the language it is, there is probably a way of achieving that by
redefining how [] works...)
> What is the Pythonic way of writing code like this? So far, I have found
> many
> v = [0 for i in range(20)]
>
> v = [0] * 20
>
> v = []
> for i in range(20): v.append(0)
>
> What should I prefer? Any other alternative?
v=[0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0]
will also work. But none of these appeal too much. I would probably do:
def newlist(length,init=0):
return [init]*length
...
v=newlist(1000)
(with the proviso that someone mentioned when the init value is complex: you
might not get unique copies of each).
> If possible, I would like to simply declare the list and fill it latter in
> my
> program, as lazily as possible (this happens notoriously when one is using
> a
> technique of programming called dynamic programming where initializing all
> positions of a table may take too much time in comparison to the filling
> of the
> array).
A sparse array? Even if an array could be constructed by assigning to
arbitrary elements, the gaps created would still need filling in with None
or Unassigned.
> 2 - If I declare a class with some member variables, is is strictly
> necessary
This is where I bail out...
--
Bartc
More information about the Python-list
mailing list