0

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!

2
  • 3
    l3 and l are just two names for the same list... Commented Aug 23, 2013 at 17:02
  • 2
    nedbatchelder.com/text/names.html Commented Aug 23, 2013 at 17:05

2 Answers 2

5

Because:

>>> l is l2
False
>>> l is l3
True

Binding the reference twice makes both names refer to the same object.

Sign up to request clarification or add additional context in comments.

Comments

4

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

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?
By deleting l2[1] you are not actually changing l2[1] object, you are removing second element from the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.