Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the smallest number in a python list and print the position

Tags:

python

list

I have a list of integer imported via a file

xy = [50, 2, 34, 6, 4, 3, 1, 5, 2]

I am aware of Python: finding lowest integer

However, I wonder how can I print the position of it instead of just finding the smallest number?

like image 539
Kit Yeung Avatar asked Jan 20 '13 09:01

Kit Yeung


3 Answers

Just use the list.index method:

print xy.index(min(xy))
# 6

If the minimum is repeated, you'll only get the index of the first occurrence, though.

like image 169
Volatility Avatar answered Nov 09 '22 04:11

Volatility


indices = [i for i, x in enumerate(xy) if x == min(xy)]    # Indices of all min occurrences
like image 33
sidi Avatar answered Nov 09 '22 03:11

sidi


Just in case someone wishes to use for loop:

xy = [50, 2, 34, 6, 4, 3, 1, 5, 2] 
t=0
for i in range(len(xy)):
    if xy[i]<xy[t]:
        t=i
print t
like image 1
Fahtima Avatar answered Nov 09 '22 05:11

Fahtima