Reputation: 275
Is there a method to retrieve the number position in the list? For example, in the following code, can we get the maximum number position?
a = [1, 2, 10, 5]
print(index_max(a))
# 2
Upvotes: 0
Views: 910
Reputation: 42143
You could use the index method:
a.index(max(a)) # 2
Or, if your list is long and you don't want to go through it twice, you can use the key parameter of the max function:
max(range(len(a)),key=lambda i:a[i]) # 2
This finds the maximum index (from range(len(a))
) but uses an indirection to determine how to compare the index. So the comparison is based on the value at each index instead of the index itself. The result is the index that has the highest value.
for details on the max() function see: https://docs.python.org/3/library/functions.html#max
Upvotes: 2
Reputation: 29
Python has an inbuilt function called index()
, which can be used to obtain the index position of an element in a list. In this instance, you may write a.index(max(a))
.
Upvotes: 0
Reputation: 103884
If you have more than one value that might be the max
you can use enumerate
:
a = [1, 2, 10, 5, 10, 6]
>>> [i for i,x in enumerate(a) if x==max(a)]
[2, 4]
Or, if you want the value included:
>>> [(i,x) for i,x in enumerate(a) if x==max(a)]
[(2, 10), (4, 10)]
Upvotes: 0
Reputation: 80
You can try
>>> print(a.index(max(a)))
2
So you are priting the index-position in list of the maximum number
Upvotes: 0
Reputation: 11486
You can use the index
method:
a.index(max(a))
Another possibility, is using enumerate
:
>>> max(enumerate(a), key=operator.itemgetter(1))
(2, 10)
Upvotes: 0