user3149650
user3149650

Reputation: 203

using the min function

If you have got something like

d1 = 5, d4 = 4

and then call the function

min(d1, d4)

how can you output d4 instead of 4? In other words, I want to output the the variable or index from the minimum function of the smallest value and not the value itself?

Upvotes: 2

Views: 133

Answers (4)

Toff'
Toff'

Reputation: 489

You could use index method of list object:

>>> mylist = [1, 2, 6, 8, 7, 4, -5, 4, 5, 6]
>>> mylist.index(min(mylist))
6

Upvotes: 0

Liam McInroy
Liam McInroy

Reputation: 4366

You could use a for loop:

minVal = min(list)
index = 0
for i in xrange(len(list)):
    if (minVal == list[i]):
        index = i
        break

Loops through, sees if it is equal, then saves the index and breaks

EDIT

You can also use a function I was unaware of under list.index()

minVal = min(list)
index = list.index(minVal)

Upvotes: 0

chepner
chepner

Reputation: 532538

You rarely want to treat your code (i.e., your variable names) as data. Use a dictionary instead:

>>> d = { 'd1': 5, 'd4': 4 }
>>> print min(d, key=d.get)
d4

Upvotes: 6

JackGibbs
JackGibbs

Reputation: 230

Here's a nice list comprehension:

d = [2, 5, -2, 7, 6, 4]
>>> [index for index, val in enumerate(d) if val == min(d)][0]
2

Upvotes: 0

Related Questions