3

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]) 
Boris BELLOC
  • 196
  • 1
  • 4
  • 15
  • How do you deal with repeated numbers? Should we assume input numbers are unique? – jpp Apr 08 '18 at 17:56
  • You do not need to sort. use `print(max(liste))` to get the max. There are plenty of build-in functions - read about them here: https://docs.python.org/3/library/functions.html – Patrick Artner Apr 08 '18 at 17:57
  • `list` objects keep no knowledge of previous states. You are going to have to keep track of that yourself – juanpa.arrivillaga Apr 08 '18 at 17:57
  • thank you for answer, repeated numbers are ok, I just need to find the highest value [99, 5, 99] -> biggest value is 99 @jpp – Boris BELLOC Apr 08 '18 at 18:00
  • Possible duplicate of [Python - Find the greatest number in a list of numbers](https://stackoverflow.com/questions/3090175/python-find-the-greatest-number-in-a-list-of-numbers) – Aran-Fey Apr 08 '18 at 18:04
  • Oops, missed the 2nd half of the question. [Here's](https://stackoverflow.com/questions/2474015/getting-the-index-of-the-returned-max-or-min-item-using-max-min-on-a-list) a more suitable dupe. – Aran-Fey Apr 08 '18 at 18:06

2 Answers2

6

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)
Primusa
  • 13,136
  • 3
  • 33
  • 53
0

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).

benjaminplanche
  • 14,689
  • 5
  • 57
  • 69