I'm using Python 2.7.12.
I'm having a problem that I think is best explained through example. Why does the .append()
behaviour of c
differ from a
and b
?
#Three different but equivalent methods to construct empty list:
a = []
for i in range(10):
a.append([])
b = [[] for _ in range(10)]
c = [[]]*10
print a
print b
print c
#Check to make sure they're equivalent. They are.
print a==b
print b==c
print a==c
#Carry out the same operation on all lists
a[1].append(6)
b[1].append(6)
c[1].append(6)
#Woah! c is now different than a and b!
print a
print b
print c
print a==b
print b==c
print a==c
OUTPUT:
[[], [], [], [], [], [], [], [], [], []]
[[], [], [], [], [], [], [], [], [], []]
[[], [], [], [], [], [], [], [], [], []]
True
True
True
[[], [6], [], [], [], [], [], [], [], []]
[[], [6], [], [], [], [], [], [], [], []]
[[6], [6], [6], [6], [6], [6], [6], [6], [6], [6]]
True
False
False