Reputation: 196
I have a list and once I sorted it to find the "biggest value", I need to display in which position this number was entered.
Any idea how to do it ?
I made this code to receive and sort the list but I have no idea how to receive the initial position of the "data".
liste = []
while len(liste) != 5:
liste.append (int(input("enter number :\n")))
listeSorted = sorted(liste)
print("the biggest number is : ", listeSorted[-1])
Upvotes: 3
Views: 730
Reputation: 15119
Another solution with sorted()
(for more generic cases e.g. if you also want the 2nd, 3rd, etc. "biggest values") :
sorted_idx_and_val = sorted(enumerate(liste), key=lambda x:x[1])
# e.g. if liste = [2, 10, 4, 6] then enumerate(liste) = [(0, 2), (1, 10), (2, 4), (3, 6)]
# and sorted_idx_and_val = [(0, 2), (2, 4), (3, 6), (1, 10)]
largest_val = sorted_ind_and_val[-1][1]
largest_val_idx = sorted_ind_and_val[-1][0]
second_largest_val = sorted_ind_and_val[-2][1]
second_largest_val_idx = sorted_ind_and_val[-2][0]
# ...
enumerate()
gives you a list containing tuples of (index, value)
.
The argument key
of sorted()
is a lambda to "preprocess" the key values to sort - here we tell sorted()
to use only value
(x[1]
) from the (index, value)
elements(x
).
Upvotes: 0
Reputation: 13498
Instead of finding the biggest value of the list by sorting the list, use use the max function:
largest_val = max(list)
To find the first occurrence of a value in a list, use the .index
method.
position = list.index(largest_val)
Upvotes: 6