[SciPy-User] python lists in combination with numpy arrays
josef.pktd@gmai...
josef.pktd@gmai...
Wed Nov 10 15:41:41 CST 2010
On Wed, Nov 10, 2010 at 4:25 PM, Martin van Leeuwen
<vanleeuwen.martin@gmail.com> wrote:
> 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()
here a always stays the same object that get overwritten
>
> vs.
>
> a = numpy.random.rand(3)
here a is a new object each time
>
>
>
> =============================
> 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])]
both entries of the list refer to the same array `a` that is
overwritten in each outer loop
my interpretation, I think it's the same behavior in this case if a
were a list (?)
Josef
>
>
> 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
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
More information about the SciPy-User
mailing list