Here is a little script:
class Any(object):
def __init__(self,x):
self.x=x
l = [Any(2),Any(3),Any(7),Any(9),Any(10)]
print(len(l))
l2=[ind for ind in l]
l3=l
print(set(l2).difference(l3))
print(l2[1]==l[1])
print(l3[1]==l[1])
del l2[1]
print(len(l))
del l3[1]
print(len(l))
Why deleting an instance of Any in l2 doesn't change l, but deleting it in l3changes l although it seems not to have any difference between l2 and l3?
Thanks a lot!
Lennart Regebro
173k45 gold badges230 silver badges254 bronze badges
asked Aug 23, 2013 at 17:00
Remi.b
18.4k34 gold badges102 silver badges181 bronze badges
2 Answers 2
Because:
>>> l is l2
False
>>> l is l3
True
Binding the reference twice makes both names refer to the same object.
answered Aug 23, 2013 at 17:03
Ignacio Vazquez-Abrams
804k160 gold badges1.4k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
l2 is a different object created from l
l3 refers to the same object as l. So changing anything in l or l3 will affect that object and therefore will affect l and l3.
2 Comments
Remi.b
l2 is a different object but both l and l2are lists of the same objects. Therefore, modifying l[2] modifies l2[2] but modifying l does not modify l2. Is it something like that?mishik
By deleting
l2[1] you are not actually changing l2[1] object, you are removing second element from the list.lang-py
l3andlare just two names for the same list...