[newbie] confused about following list assignment

K

Kenny

Hello,

I wanted a list with unique element at postion zero, so I wrote a little
code that I thought would do this (see below).
.... x=random.random()
.... print x
.... a[0]=str(x*10)
....
0.710829738051
0.896195451411
0.0971075321793
0.882219628625
[['8.82219628625', 'c', 'd'], ['8.82219628625', 'c', 'd'],
['8.82219628625', 'c', 'd'], ['8.82219628625', 'c', 'd']]

Can someone explain why all the position zeros are being assigned the same
value of x?

List a was generated previously as
a=[]
b=['t','c','d']
for i in range(5):
.... a.append(b)

Regards,

Kenny

*******************************************************************************
tout casse, tout passe, tout lasse.
*******************************************************************************
 
K

KAP

Can someone explain why all the position zeros are being assigned the
same value of x?

Try >>> for x in range(len(a)): print id(a[x][0])

to see that all reference the same object. The last assignment you made
with "a[0]=str(x*10)" is the new object that each of the above will
reference.

You need to create some copies first. Your code will work the way you want
by changing:

.... a.append(b)

to this

.... a.append(b[:])

Ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top