oceandye
oceandye

Reputation: 319

How to get max() to return variable names instead of values in Python?

So I would like to get the maximum value from 3 variables, x,y,z.

x = 1
y = 2
z = 3
max(x, y, z)  # returns 3 but I want "z"

However this returns the value of z i.e 3. How do I get the name of the variable e.g. "z" instead?

Thanks

Upvotes: 7

Views: 23884

Answers (6)

ThelmaI
ThelmaI

Reputation: 1

After using max, you can write if statements.

highest = max(x,y,z)

if highest == x:
  print('x')

And so forth

Upvotes: -1

Nouman
Nouman

Reputation: 7303

Make a dictionary and then use max. Also works with min. It will return you the variable name in the form of string.

>>> x = 1
>>> y = 2
>>> z = 3
>>> var = {x:"x",y:"y",z:"z"}
>>> max(var)
3
>>> var.get(max(var))
'z'
>>> var.get(min(var))
'x'
>>>

Upvotes: 11

ashish trehan
ashish trehan

Reputation: 433

Create a List of the numbers then type max() around the list.

Upvotes: -3

Ma0
Ma0

Reputation: 15204

This is not at all recommended but you can use the globals() dictionary which keeps track of all variables that are either built-ins or have been defined by the user:

x = 1
y = 2
z = 3

variables = {k: v for k, v in globals().items() if isinstance(v, int)}
max_value = max(variables.values())
res = next(k for k, v in variables.items() if v == max_value)

which results in:

print(res)  # z

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599520

Use a dictionary and get the maximum of its items, using a key function.

d = {'x':1, 'y':2, 'z':3}
max(d.items(), key=lambda i: i[1])

Upvotes: 3

dfundako
dfundako

Reputation: 8314

You could put them into a dictionary and use max with a key:

dict1 = {'x':1, 'y':2, 'z':3}
max(dict1, key=dict1.get)

But think through the ramifications of this. What if you have the same val multiple times, and other edge cases.

Upvotes: 8

Related Questions