Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map function or lambda does not work as expected in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading