Many newbie questions regarding python

nn pruebauno at
Fri Oct 8 17:39:54 CEST 2010

On Oct 7, 7:10 pm, Rogério Brito <rbr... at> wrote:
> Hi there.
> I am used to some languages like C, but I am just a complete newbie with Python
> and, while writing some small snippets, I had encountered some problems, with
> which I would sincerely appreciate any help, since I appreciate this language to
> write my "running pseudocode in" and I am seriously thinking of using it to
> teach some algorithms classes.
> 1 - The first issue that I am having is that I don't seem to be able to, say,
> use something that would be common for people writing programs in C: defining a
> one-dimensional vector and only initializing it when needed.
> For instance, in C, I would write something like:
> int v[20];
> for (i = 0; i < 20; i++)
>     v[i] = 0;
> Note that I only define the vector v (and its size) at the beginning but
> initialize it latter during the code per-se.
> 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. Of course, the main difference between the two snippets is
> that, in C, I declared v to have 20 positions, while in python I initialized it
> to be the empty list and, indeed, it has an empty set of indexes.
> What is the Pythonic way of writing code like this? So far, I have found many
> alternatives and I would like to write code that others in the Python community
> would find natural to read. Some of the things that crossed my mind:
>     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?
> 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).

Just to emphasize what Andreas said:
v = [0] * 20
is nice and good,

don't do this
v = [ [] ] * 20

or this
v = [ {} ] * 20

until you have played around with it on the interactive prompt to
understand how it works.

The difference of behavior of mutable vs immutable objects is one of
the main pitfalls for beginners in Python. Everything is very
consistent once you understand the assignment semantics, but it really
confuses people accustomed to other languages that work differently.

More information about the Python-list mailing list