1

I'm trying to build a game in pygame with OOP and I got into a problem.

The problem is that when I tried to pop the last item from the list, self.list got popped as well.

This is a simpler version of the problem:

class Example(object):
    def __init__(self):
        self.list_that_shouldnt_get_popped = [1,2,3,4,5]

    def pop_equal_list(self):
        list_that_should_get_popped = self.list_that_shouldnt_get_popped
        list_that_should_get_popped.pop()

And when you try to run it the outcome is this:

Ex = Example()
Ex.pop_equal_list()

print(Ex.list_that_shouldnt_get_popped.__len__())



Output : 4

I expect that the length of self.list_that_shouldnt_get_popped will be 5 and not 4 meaning I would like it to not pop.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
shnap
  • 175
  • 1
  • 1
  • 10

1 Answers1

-1

In Python a list variable only holds a reference to the list, so when you do:

list_that_should_get_popped = self.list_that_shouldnt_get_popped

you are only copying the reference to the list that self.list_that_shouldnt_get_popped references to the variable list_that_should_get_popped.

You should instead assign to list_that_should_get_popped with a new list:

list_that_should_get_popped = self.list_that_shouldnt_get_popped[:]
blhsing
  • 91,368
  • 6
  • 71
  • 106