Search code examples
pythonmaxmin

How to use min() and max() functions to print the variable name instead of the value?


This is my code for bot-card game.

card_5 = 3 #all variable names
card_6 = 4
card_7 = 5
card_8 = 6
player_card_list = [card_5,card_6,card_7,card_8]#list of variables
min_player_card = int(min(player_card_list))#i want this variable to print the variable name
max_player_card = int(max(player_card_list))

Solution

  • If you want a name associated to a value, you're looking for a dict, not a list. Consider

    player_card_dict = {
        "card_5": card_5,
        "card_6": card_6,
        "card_7": card_7,
        "card_8": card_8,
    }
    

    Then we can use the optional key argument on min or max to control how the comparison is done.

    min_player_card = min(player_card_dict, key=lambda name: player_card_dict[name])
    max_player_card = max(player_card_dict, key=lambda name: player_card_dict[name])