[SciPy-User] python lists in combination with numpy arrays

Martin van Leeuwen vanleeuwen.martin at gmail.com
Wed Nov 10 16:25:33 EST 2010


Dear All,

I hope some of you could help me out understanding the following.
I am a little puzzled about something I found using numpy in
combination with standard python lists.
The following two methods give different outputs on my machine.
While the first method surprisingly overrides the python list instead
of appending, the second method appends as I would expect.
The only real difference between the methods is the line:

for j in range(3): a[j] = numpy.random.rand()

vs.

a = numpy.random.rand(3)



=============================
import numpy

print "first method"

lst=[]
a = numpy.zeros(3, dtype=float)
for i in range(2):
    for j in range(3): a[j] = numpy.random.rand()
    print "three random values:", a
    lst.append(a)
    print 'current list:', lst
    print '\n'

print "second method"

lst=[]
for i in range(2):
    a = numpy.random.rand(3)
    print "three random values:", a
    lst.append(a)
    print 'current list:', lst
    print '\n'


==========IDLE output==========
first method
three random values: [ 0.87115972  0.26259606  0.34981352]
current list: [array([ 0.87115972,  0.26259606,  0.34981352])]


three random values: [ 0.48827773  0.91841208  0.81756918]
current list: [array([ 0.48827773,  0.91841208,  0.81756918]), array([
0.48827773,  0.91841208,  0.81756918])]


second method
three random values: [ 0.88553281  0.92494531  0.34539655]
current list: [array([ 0.88553281,  0.92494531,  0.34539655])]


three random values: [ 0.87463742  0.49128832  0.89126926]
current list: [array([ 0.88553281,  0.92494531,  0.34539655]), array([
0.87463742,  0.49128832,  0.89126926])]


============================
As you can see, in the second iteration of the first method the first
entry in the list gets overridden with the new array, and the same
array then also get appended to that list. In the second method, the
new array gets appended to the list and the first entry of the list
remains as it was.

Thanks for any help on this.

Martin



More information about the SciPy-User mailing list