newbie list handling question

T

Teuvo Eloranta

Hi,

Any help to this?


## why a changes also when only av should change?

## outcome is:
## av is [[1, 10], [2, 20], [3, 30]]
## a is [[1, 10], [2, 20], [3, 30]]
## av is [[1, 20], [2, 20], [3, 20]]
## a is [[1, 20], [2, 20], [3, 20]]

a = [[1, 10], [2, 20], [3, 30]]
av = []

for i in a:
av.append(i)
#av = a[:]

print "av is", av
print "a is", a

aver = 20

#for y in av:
# y[1] = aver

for i in range(len(av)): # this should change only av, not a?
av[1]=aver

#for i in range(len(a)): # this solution works!
# av.append([i+1,aver])

print "av is", av
print "a is", a


Thank's in advance.

-Teuvo
 
D

Diez B. Roggisch

a = [[1, 10], [2, 20], [3, 30]]
av = []

for i in a:
av.append(i)
#av = a[:]

here you don't store a _copy_ of the contained list, but a reference
instead. Change av.append(i) to av.append(list(i)), and you should get a
copy of the list.


Diez
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top