Reputation: 17
If I execute this code, the following error message occurs:
IndexError: list index out of range python
def reverse_invert(lst):
inverse_list = []
for i in lst:
if isinstance( i, int ):
inverse_list.append(lst[i])
#print(inverse_list)
print(i)
else:
break
return inverse_list
Why is it?
Upvotes: 1
Views: 1183
Reputation: 16174
for i in lst:
will iterate the elements of lst
.
If you want to iterate indexes, use
for i in range(len(lst)):
If you want both the element and the index, use enumerate
:
for i, el in enumerate(lst):
Upvotes: 1
Reputation: 3766
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was
[1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
Upvotes: 0
Reputation: 27869
List comprehension would work fine:
a = [1, 'a', 2, 3]
print [d for d in a[::-1] if isinstance(d, int)]
And if you want to reverse it just tiny change would do:
a = [1, 'a', 2, 3]
print [d for d in a[::-1] if isinstance(d, int)]
Or maybe I missed your point.
Upvotes: 0
Reputation: 318
You are iterating the elements of list but trying to use the element as index. You should change your code like this:
def reverse_invert(lst):
inverse_list = []
for i in lst:
if isinstance( i, int ):
inverse_list.append(i) # changed this one.
#print(inverse_list)
print(i)
else:
break
return inverse_list
Upvotes: 0