Python Forum
Theory behind referencing a dictionary rather than copying it to a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Theory behind referencing a dictionary rather than copying it to a list
#2
Moving the dict instantiation into the loop fixed it. Previously, you were referencing the same dict multiple times in a list. That means any update to the dict will update every reference in the list because they all get their information from the same memory location.

Inside the loop, the dict instantiation creates a new dict stored at a different memory location each time. Even though you're appending the same variable to the list, that variable has a different reference every time the loop runs.

out= []
for x in range(10):
    example = {}
    out.append(example)
    print(id(example))
Output:
52431536 55345824 55345728 55345680 55346208 55347456 55346256 55346304 55346352 55346400
Compared to the original:

out = []
example= {}
for x in range(10):
    out.append(example)
    print(id(example))
Output:
55345968 55345968 55345968 55345968 55345968 55345968 55345968 55345968 55345968 55345968
Reply


Messages In This Thread
RE: Theory behind referencing a dictionary rather than copying it to a list - by stullis - Mar-24-2020, 06:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 2 653 Apr-29-2024, 04:38 PM
Last Post: Calab
  Dictionary in a list bashage 2 610 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 759 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Copying the order of another list with identical values gohanhango 7 1,216 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  Copy List Not Copying BAbdulBaki 3 674 Aug-19-2023, 02:03 AM
Last Post: perfringo
  How to add list to dictionary? Kull_Khan 3 1,058 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  Queuing Theory in Python NOLA_Saints 0 794 Feb-22-2023, 11:42 PM
Last Post: NOLA_Saints
  check if element is in a list in a dictionary value ambrozote 4 2,049 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 2,056 Apr-28-2022, 06:59 AM
Last Post: buran
  name 'lblstatus' is not defined when referencing a label KatManDEW 4 1,597 Apr-21-2022, 12:33 PM
Last Post: KatManDEW

Forum Jump:

User Panel Messages

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