1

I am making a little game in pygame, for use in reinforcement learning (openAI gym) but I'm encountering an issue with lists/dictionaries. I presume this is to do with empty lists all pointing to the same memory address, but I do not understand why/how or how to avoid it in this scenario.

Ultimately I want to be able to use empty lists or dicts for this, I am trying to group a list of tuples of the form ((int1, int2), int3)) by their second element (int3).

I have tried using copy() when initializing the empty array but with no difference. I did not find/understand anything useful from tutorials or docs pages, so I would greatly appreciate a brief explanation of how to avoid this issue.

def works(t):
    lst = [[1],[2],[3]]
    lst[1].append([x for x in t if x[1]==1])
    return lst

def does_not_work(t):
    lst = 3*[list()]
    lst[1].append([x for x in t if x[1]==1])
    return lst

t = [(('a'), 0), (('b'), 1), (('c'), 1), (('d'),2)]
print('Expected Result:')
print(works(t))
print('Confusing Result:')
print(does_not_work(t))
Expected Result:
[[1], [2, [('b', 1), ('c', 1)]], [3]]
Confusing Result:
[[[('b', 1), ('c', 1)]], [[('b', 1), ('c', 1)]], [[('b', 1), ('c', 1)]]]
Reegan Miranda
  • 2,879
  • 6
  • 43
  • 55
skinnypete
  • 35
  • 4

1 Answers1

4

lst = 3*[list()]

This creates 3 references to the same list. Use lst = [ [] for i in range(n) ]

clubby789
  • 2,543
  • 4
  • 16
  • 32