Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do objects work?
#3
An important point that comes from this - as long as an object has a reference pointing to it, it is live and kept. When there are no references it is available for reuse (garbage collection). The equals sign establishes a reference to the object. So:
x = [5,6]
print(x)
y = x
print(y)
x.append(7)
print(y)
x = [3]
print(x,y)
gives output of
Output:
[5, 6] [5, 6] [5, 6, 7] [3] [5, 6, 7]
The append in line 5 adds a 7 to the list referenced by x. It is the same list referenced by y (the line y=x does NOT make a copy, rather adds a second reference to the same object). So, printing y shows the 7 even though you did not modify y anywhere. When you reassign x to a different object in line 7, the first list remains referenced by y and the new list is referenced by x.
Reply


Messages In This Thread
How do objects work? - by pyThon_ - Oct-24-2019, 08:56 AM
RE: How do objects work? - by Gribouillis - Oct-24-2019, 09:35 AM
RE: How do objects work? - by jefsummers - Oct-24-2019, 02:01 PM
RE: How do objects work? - by pyThon_ - Oct-24-2019, 03:06 PM
RE: How do objects work? - by snippsat - Oct-24-2019, 03:41 PM
RE: How do objects work? - by pyThon_ - Oct-24-2019, 03:54 PM
RE: How do objects work? - by Gribouillis - Oct-24-2019, 04:16 PM
RE: How do objects work? - by pyThon_ - Oct-24-2019, 06:52 PM
RE: How do objects work? - by snippsat - Oct-24-2019, 04:34 PM
RE: How do objects work? - by Gribouillis - Oct-24-2019, 10:05 PM
RE: How do objects work? - by pyThon_ - Oct-24-2019, 11:13 PM
RE: How do objects work? - by Gribouillis - Oct-25-2019, 06:13 AM
RE: How do objects work? - by jefsummers - Oct-25-2019, 03:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How do integer objects work? pyThon_ 2 1,938 Oct-22-2019, 01:36 AM
Last Post: wavic
  Python - Make Json objects to work concurrently through Threads? WeInThis 0 2,649 Sep-22-2017, 11:31 AM
Last Post: WeInThis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020