Python Forum
I can't understand this problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I can't understand this problem
#4
Lists are also "reference pointers." A reference pointer stores the memory reference for the data instead of containing copies of the data. It's a more advanced concept that's much more prevalent in other programming languages (C, Go, Java, etc.). Basically, when you pass the list into the function, the function doesn't make a local copy of the data. Rather, it looks directly at the memory space where that list is stored. This means that any alteration made within the function is made directly to the original list.

This gets really interesting when you do something like this:

in_list = []
out_list = []

for x in range(4):
    in_list.append(x)
    out_list.append(in_list)

print(out_list)
It will print:
Output:
[[0,1,2,3],[0,1,2,3],[0,1,2,3],[0,1,2,3]]
The loop appends a copy of the in_list to the out_list each time. It also appends new data to the in_list. When we print the out_list, we may expect four copies of the in_list at different stages of the iteration: [[0],[0,1],[0,1,2],[0,1,2,3]]. Instead, we get four copies of the in_list with all the numbers in each copy. This is because the memory reference for the in_list has been appended four times and that memory reference can only contain the most recent data stored there.
Reply


Messages In This Thread
I can't understand this problem - by muhammedkhairy - Dec-23-2018, 07:37 PM
RE: I can't understand this problem - by ichabod801 - Dec-23-2018, 08:36 PM
RE: I can't understand this problem - by stullis - Dec-23-2018, 09:35 PM
RE: I can't understand this problem - by ichabod801 - Dec-23-2018, 09:44 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Couldn't really understand the problem Batselot 1 2,393 Dec-13-2018, 07:59 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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