Many newbie questions regarding python

Carl Banks pavlovevidence at gmail.com
Fri Oct 8 01:25:16 CEST 2010


On Oct 7, 4:10 pm, Rogério Brito <rbr... at ime.usp.br> wrote:
[snip]
>
>     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?

The Pythonic way is to not to preinitialize the list at all.  Don't
put anything in the list until you have the data you need.

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

So, if I understand you, you are thinking of your list as a table with
dynamically calculated entries, and want to calculate the entries upon
request.

Three possibilities:

1. Initialize the list using v = [None]*n (I recomment using None
instead of 0 for this, in most cases)

2. Use a dict instead.  Dict items pop into existence if you assign
with a key that doesn't exist.

v = {}

Then you can do

v[1] = a
v[10] = n
v[999] = c

3. Consider numpy, which allows preallocation of lists:

v = np.zeros(100)


[snip]
> For instance, if I
> define:
>
> class C:
>     f = 1
>     def g(self):
>         return f
>
> I get an annoying message when I try to call the g method in an object of type
> C, telling me that there's no global symbol called f. If I make g return self.f
> instead, things work as expected, but the code loses some readability.
>
> Is there any way around this or is that simply "a matter of life"?

Matter of life.  It's that way by design.


Carl Banks



More information about the Python-list mailing list