0

I was doing a program in Python a little puzzle where the user only have to order the numbers, whatever in the program I create a list of lists. The main list it's empty, I create a method where the program fill the list with another 4 lists using a for with an enumerate and when the account comes every 4 times save the secondary list inside the main list and here comes where need someone explain me or if it's a bug.

I clean the secondary list but the main list cleaning to and I don't know what's going on only when I create a new list works but with the other method doesn't.

class Puzzle:
    
    def __init__(self, array):
        self.array = array
        self.account = 0
    
    def fillPuzzle(self):
        """Method that fill the list of lists"""
        # account = self.account
        newlist = list()
        for account, number in enumerate(range(1,17),start=1):
            number = str(number) if number != 16 else 'X'
            newlist.append(number)
            if account in (4,8,12,16):
                self.array.append(newlist)
                newlist.clear()# here it's the problem, if i use newlist = list() works
        return self.array
    def showArray(self):
        print(f"\nLista : {self.array}")

emptylist = list()
newpuzzle = Puzzle(emptylist)
# 
newpuzzle.showArray()
newpuzzle.fillPuzzle()
newpuzzle.showArray()
  • 2
    It is not a python bug. –  Feb 25 '21 at 21:23
  • 3
    The issue is that you are putting the very same list 4 times into the outer list. Thus, changing it in one place, will change it in every place. If you instead do as in your comment, you are creating a new list, and then it works. – JohanL Feb 25 '21 at 21:25
  • Yes that answer my question, thanks that explain me a lot – Alquimistázul Feb 25 '21 at 21:27

0 Answers0