[Tutor] Calling a function

Max Noel maxnoel_fr at yahoo.fr
Fri Jun 10 05:38:26 CEST 2005


On Jun 9, 2005, at 07:45, Kevin Reeder wrote:

> I'm having trouble with this code which is meant to run a time
> comparison between two similar functions. The first module is
> makezeros.py
>
> def lots_of_appends():
>     zeros = []
>     for i in range(10000):
>     zeros.append(0)
>
> def one_multiply():
>     zeros = [0] * 10000

     Note that your functions don't do the same thing. The first one  
builds the list properly, but the second builds a list out of  
references to the same object -- that is, the 10000 zeros in your  
resulting second list are actually the same object.
     As long as you're working with immutable types (numbers,  
strings) you won't notice there's a problem, but consider the following:

 >>> a = [[0]] * 10
 >>> a[0].append(1)
 >>> a
[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0,  
1], [0, 1]]

[0] is a list -- therefore, a mutable object: you can apply  
modifications to it. So, the list is actually a list of ten  
references to the same object -- [0]. When you run one of its methods  
that modifies it, since all references point to it, all members of  
the list seem to be modified as well -- but they're actually one  
single object that's present 10 times in the list.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge  
a perfect, immortal machine?"



More information about the Tutor mailing list