Ask coding questions

← Back to all posts
How to find the maximum variable in a list in python
MikeJMS8910 (234)

So here is my code -

var1 = 1
var2 = 2
var3 = 3
varList = [var1, var2, var3]

I want to find which variable has the highest value but then get the variable. This means that I can't use max because the value would be 3 instead of var3, but I want var3.

Comments
hotnewtop
RYANTADIPARTHI (6018)

Solution

try this code.

var1 = 1
var2 = 2
var3 = 3

variable_name = [k for k, v in locals().items() if v == var1][0] 
variable_name1 = [k for k, v in locals().items() if v == var2][0] 
variable_name2 = [k for k, v in locals().items() if v == var3][0] 

varList = [variable_name, variable_name1, variable_name2]

print(max(varList))

like that.
That should work

MikeJMS8910 (234)

@RYANTADIPARTHI yes I tried this but then got an error which was like index out of range

MikeJMS8910 (234)

@RYANTADIPARTHI ok heres the code - https://repl.it/@MikeJMS8910/Machine-Learning#main.py - the part that I am working in is line 125

RYANTADIPARTHI (6018)

@MikeJMS8910 maybe remove the [0] from the end.

MikeJMS8910 (234)

@RYANTADIPARTHI ok I did it but now there are no errors but the max value keeps coming out as []

Coder100 (18818)

you can't actually know the variable names, it just won't work

use something like a dict:

map = {
  'var1': 1,
  'var2': 2,
  'var3': 3
}

max = ... determine somehow ...
map[max] += 1

of course, that is the closest you will get.

It just isn't practical to be able to get the variable, 100% of the time it's a mistake.

IOP3 (850)

You need to do print(max(var_List))

MikeJMS8910 (234)

@IcingHackz thats not what I mean
if I were to do that it will just give me 3 since that is the top value but I also want to find which variable holds the highest value

IOP3 (850)

@MikeJMS8910 I don't think that's possible to get the variable with the highest value, you only can get the value that's the highest. :P

MikeJMS8910 (234)

@IcingHackz do you know anyone who could know?....

IOP3 (850)

@MikeJMS8910 probably the people who have the most cycles like @Coder100, @RYANTADIPARTHI, or @Bookie0

IOP3 (850)

@Coder100 he asked a question, I answered it

RYANTADIPARTHI (6018)

@MikeJMS8910

try this code. It works.

var1 = 1
var2 = 2
var3 = 3

variable_name = [k for k, v in locals().items() if v == var1][0] 
variable_name1 = [k for k, v in locals().items() if v == var2][0] 
variable_name2 = [k for k, v in locals().items() if v == var3][0] 

varList = [variable_name, variable_name1, variable_name2]

print(max(varList))