简体   繁体   中英

Why does list become empty after returning it from function?

When returning a list of tuples from a class method, the returned list becomes empty.

I have tried printing the list to sys.stderr just before returning it (here, it contains all the tuples) and after receiving it on the calling side (here, all tuples are gone). I have also tried changing data type to a tuple of tuples, but the problem remains. I have double checked so that I am returning the correct variable. There are no similar variable names, but I have also tried changing the variable name without success.

I am running my code on Python 3 in Codeingame's environment. This is the specific challenge I am coding for: https://www.codingame.com/ide/puzzle/tic-tac-toe

class Boardstate:
    def get_valid_moves(self):
        valid_moves = []
        for row in range(3):
            for col in range(3):
                sq = self.squares[row][col]
                sq_valid_moves = [
                    (row*3 + j, col*3 + i) for (j, i) in sq.get_valid_moves()
                ]
                valid_moves.extend(sq_valid_moves)
        print(valid_moves, file=sys.stderr)
        return valid_moves

valid_moves = temp_state.get_valid_moves() #temp_state is an instance of Boardstate
print(valid_moves, file=sys.stderr)

I expect to see the same list of tuples outside the class method as I see inside it before returning.

Try with adding self to valid_moves like this:

class Boardstate:
    def get_valid_moves(self):
        self.valid_moves = []
        for row in range(3):
            for col in range(3):
                sq = self.squares[row][col]
                sq_valid_moves = [
                    (row*3 + j, col*3 + i) for (j, i) in sq.get_valid_moves()
                ]
                self.valid_moves.extend(sq_valid_moves)
        print(self.valid_moves, file=sys.stderr)
        return self.valid_moves

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM