[Tutor] Generate array, different results

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Sep 21 21:55:50 CEST 2012


Pavel Andreev wrote:
> Hello all
> A question from very beginner.
> I generate a simple example array and then print its elements on the screen.
> 
> f=[[0]*3]*3                      # array initialization

Your problem is above. Let us rewrite the above line as
a = [0]*3
f = [a]*3 

Variable `a` is a new list with 3 copies of the contents in the
list which is 0 (i.e. there are 3 zeros in the new list). 
There is no problem here because 0 is an immutable (cannot be 
changed) object. Now in the second line, the variable `f` 
is a new list with 3 copies of `a`. This basically boils
down to the equivalent of:
f = [ a for _ in xrange(3) ] # OR
f = [ a, a, a ]

You can see they are the same object by using is.

>>> f[0] is f[1]
True

`f[0]` and `f[1]` are both bound to the same list object.
Since lists are mutable objects, when you change `f[0]` you
are actually changing the object underlying `f[1]`.
You can fix your problem by the following instead.

f = [ [0]*3 for _ in xrange(3) ]


> for i in range(3):
>     for j in range(3):
>         f[i][j]=str(i)+str(j)    # make simple example array
>         print f[i][j],           # print resulting elements
>     print '\n'
> 
> 
>  00   01   02
> 
>  10   11   12
> 
>  20   21   22
> 
> 
> So I generate element in loop and then print it and see all is ok.

The reason your loop works initially is that you are setting the 
value you want immediately before you print it. With each iteration
of `i` you are discarding the previous value. You can debug what is 
happening if you print `f`  at each step in the loop instead of 
`f[i][j]`. It will probably make a lot more sense than my explanation. 

 
> But after that if I print the whole generated array, I see different
> result with constant first number, as if "i" variable does not vary
> and equals to "2". What is wrong?
> 
> >>> print f
> 
> [['20', '21', '22'], ['20', '21', '22'], ['20', '21', '22']]
> 
> I use python 2.7


Feel free to ask for clarification if that explanation did not 
make sense.



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list