简体   繁体   中英

Error: list index out of range

the following function is supposed to give you out all the numbers in a list that do correspond to it's index ie Index 0 = 0, and append this number in a list.

def Utility(l):
Total = []
for i in l:
    if i == l[i]:
        Total.append(i)
    else:
        pass
return Total

I do get an Error: list index out of range.

for i in l iterates over the list l . So on every iteration you assign an element from the list to i .

If you want for indexes, you need to use enumerate .

for idx, ele in enumerate(l):
    # your code

enumerate will return the index and the item on every iteration. Your code can be written such

def Utility(l):
Total = []
for idx, ele in enumerate(l):
    if idx == ele:
        Total.append(idx)

The else clause is useless and can be removed

You are iterating over the elements of l , not iterating over the indices:

for i in [5,6,7]:
    print(i)
> 5
> 6
> 7

You should use enumerate :

for i, num in enumerate([5, 6, 7]):
    print(i, num)
> 0 5
> 1 6
> 2 7

Your code should be :

def Utility(l):
  Total = []
  for i in range(len(l)):          #point of interest
    if i == l[i]:
        Total.append(i)
    else:
        pass
  return Total

#driver values

IN : l = [0,1,4,6]
OUT : [0,1]

The fault in your code is that when you do for i in l , the i value is the elements in l , and since those values can be greater than then number of elements in l , it will through up an Error . Like:

l=[5]
for i in l:
   print(i)
   #5
   print(l[i])           #l[5]
   #IndexError: list index out of range

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