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!

Lennart Regebro
173k45 gold badges230 silver badges254 bronze badges
asked Aug 23, 2013 at 17:00
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.

answered Aug 23, 2013 at 17:03
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.

martineau
124k29 gold badges181 silver badges319 bronze badges
answered Aug 23, 2013 at 17:03

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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.