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)