The following code below returns the position of the first lowest number in a list.
xy = [50, 2, 34, 6, 4, 3, 1, 5, 2, 1, 10 ,1]
t=0
for i in range(len(xy)):
if xy[i]<xy[t]:
t=i
print(t)
out: 6
I would like to get the positions of all the lowest numbers. In this case it should be 6,9,11. How do I go about in base Python?
You could use Python's predefined min function to get the minimum value in the list, then get the indices of the values equal to that minimum using a list comprehension, like this:
xy = [50, 2, 34, 6, 4, 3, 1, 5, 2, 1, 10 ,1]
lowest = min(xy)
positions = [i for i, v in enumerate(xy) if v == lowest]
print(positions) # ==> [6, 9, 11]
This should be the most CPU efficient solution because it runs the list only once. @Mr Geek's solution should be slightly better on memory because his way only produces one list of results.
xy = [50, 2, 34, 6, 4, 3, 1, 5, 2, 1, 10 ,1]
min_val = sys.maxsize
result = []
for index, num in enumerate(xy):
if num < min_val:
min_val = num
result = [index]
elif num == min_val:
result.append(index)
result now contains [6, 9, 11]
Whenever we find a new minimum value, we clear the list of results and add the new number. Whenever we find the same number, we add it to the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With