moves.remove() vs. moves = moves.remove()
Kenneth removed the pertinent items from the moves list "in place":
def get_moves(player): moves = ["LEFT", "RIGHT", "UP", "DOWN"] x, y = player if y == 0: moves.remove("UP") if y == 4: moves.remove("DOWN") if x == 0: moves.remove("LEFT") if x == 4: moves.remove("RIGHT") return moves
but I originally had the get_moves function written as:
def get_moves(player): moves = ["LEFT", "RIGHT", "UP", "DOWN"] x, y = player if y == 0: moves = moves.remove("UP") if y == 4: moves = moves.remove("DOWN") if x == 0: moves = moves.remove("LEFT") if x == 4: moves = moves.remove("RIGHT") return moves
where I set moves = moves.remove()
I would have thought these basically are saying the same thing, but when I originally tried running the code I got a "TypeError: can only join an interable", or something like that. I'm confused...what's the difference between the two?
Ryan S27,269 Points
The difference depends on whether or not a method returns a value. In the case of
.remove(), it does not return a value, it only modifies the iterable to which it is applied. The same is true for
So in your version, the "moves" variable will be of type "NoneType" because nothing was returned in the method. Your error is not likely a encountered inside the "get_moves" function, because what you are attempting to do will not produce an error, but its probably raised outside where it is being called, since "moves" will have a value of None.
.pop() method, on the other hand, does return a value so you can pull out an item and store it in a variable. However, this wouldn't be appropriate for the logic of the function, since you want to utilize the remaining moves in the list, not the one you removed.
So even if
.remove() returned a value, it would essentially invert the logic of the game by grabbing the only move that you shouldn't be able to use, rather than leaving behind the ones you should.
Hope this clears things up.
Not only did it clear things up, you also turned on a lightbulb regarding the .pop() method. Thanks for the great reply!