My code does not work as expected. My partial code looks like this:
lst_of_players = []
class Player:
def __init__(self, username):
self.username = username
self.level = 1
lst_of_players.append(self)
def level_up(self):
self.level = 1
player1 = Player("Player 1")
player2 = Player("Player 2")
player3 = Player("Player 3")
def level_up_all_players():
map(lambda player: player.level_up(), lst_of_players)
I thought the players' levels would be leveled up by 1 when i call level_up_all_players func, but it does not. When I print the levels of players, they still had the levels they had before calling the function.
CodePudding user response:
map()
used to work as you expected in Python 2.7, but now map()
is lazy in Python 3.x, so you have to force it to work. Put the last line of your level_up_all_players()
inside list()
, like this:
list(map(lambda player: player.level_up(), lst_of_players))
However, this is not recommended. It's not usually a good practice to use map()
just for the side effects (in your case, code is just adding 1 to player's level).
Normally, you work with the result that is produced using map()
.
So, I really think you should use for
loop for this kind of work, and it's easier to read than map
with lambda
for me and for many other people:
for player in lst_of_players:
player.level_up()
Update
If you really want to achieve the same thing with just one line, you can do this:
for player in lst_of_players: player.level_up()
And I found a similar SO post that is about map()
in Python. Please take a look at it: link to the post
CodePudding user response:
map
is lazy: the function isn't applied until you actually iterate over the map
object.
Neither map
nor a list comprehension, though, should be used solely for the side effect of the function being called on a value. Only use it if you want the return value of each function call. Just use a regular for
loop instead:
for p in lst_of_players:
p.level_up()