-4

I have tried to use the max code but it printed out the largest number not the variable name.

a=3
b=4
c=7
d=6
e=8

max(a,b,c,d,e)

this is the code I've tried but it printed 8 instead of e. forgot to add that my values for a b c etc came from a loop so im not suppose to know their values myself...

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    Yes, that's what it'll do. What do you need the variable _name_ for? – deceze Oct 25 '17 at 09:29
  • Well, you'll need to call `max` on a dictionary and return the key corresponding to the largest values. Remember that names are just references to objects. – cs95 Oct 25 '17 at 09:33
  • 1
    Concerning your edit: If the values come from a loop, the loop should be part of the minimal working example. How can you even assign variable values within a loop? – Raimund Krämer Oct 25 '17 at 09:53
  • 1
    Don't change your question midway. That wastes everyone's time. Just close this question, accept an answer, and open a new one. – cs95 Oct 25 '17 at 10:10
  • it wont let me as it says wait for 3 days – yanpingguan2002 Oct 25 '17 at 10:33

3 Answers3

2

You need to use a dictionary or a named tuple to do something like that.

>>> my_list = {'a': 1, 'b': 2, 'c': 3}
>>> max(my_list, key=my_list.get)
'c'

Let me know if there are any other methods.

pissall
  • 7,109
  • 2
  • 25
  • 45
0

Try this

 dct={'a':3 ,'b':4 ,'c':7 ,'d':6 ,'e':8}
    for i, j in dct.iteritems():
            if j == max(dct.values()):
            print i
Sandeep Lade
  • 1,865
  • 2
  • 13
  • 23
  • That's pretty darn inefficient and somewhat inaccurate (`j` and `max(..)` must simply be equal, not _the same_, so may in fact not refer to the same entry). – deceze Oct 25 '17 at 09:37
  • Not very efficient and not pythonic, though. – Raimund Krämer Oct 25 '17 at 09:37
  • If you want to use this non-pythonic way, then at least you should not call `max(dct.values())` within the loop, but once before it, then only check for equality in the loop. – Raimund Krämer Oct 25 '17 at 09:42
0

From this question, there seems to be a way to retrieve the name of your variable (see caveat below before using):

a = 3
b = 4
c = 7
d = 6
e = 8

m = max(a, b, c, d, e)

for k, v in list(locals().items()):
    if v is m:
        v_as_str = k
        break

v_as_str

output:

'e'

Caveat:

This may work if you can be sure that there are no other (unrelated) variables with the same value as the max of a to e somewhere in your code, and appearing earlier in the locals. Thanks to @D.Everhard & @asongtoruin in the comments

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80