简体   繁体   中英

Find the smallest element in a list

I would like to find the smallest value of list a . I know that there is a function like min() to find the value but I would like do it work with a for -loop. I get the error Index out of range with the if -Statement, but I don't know why.

a = [18,15,22,25,11,29,31]
n = len(a)

tmp = a[0]
for i in a:
   if(a[i] < tmp):
      tmp = a[i]
      print(tmp)

When you iterate over a list in Python ( for e in l: ), you do not iterate over the indices but over the elements directly. So you should write:

for e in a:
    if(e < tmp):
        tmp = e
        print(tmp)

As already said, you mixed iteration over elements and looping over indexes. The solution for iteration over elements was already presented, so for completeness I would like to write the other solution:

a = [18,15,22,25,11,29,31]
n = len(a)

tmp = a[0]
for i in range(n):
    if(a[i] < tmp):
        tmp = a[i]
        print(tmp)

Edit: changed xrange to range as per comment bellow.

a = [18,15,22,25,11,29,31]
print(min(a))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM