python : list index out of range error while iteratively popping elements
You are reducing the length of your list l
as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.
It looks like what you want to do is:
l = [x for x in l if x != 0]
which will return a copy of l
without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x
, since non-zero numbers evaluate to True
.
There is no such thing as a loop termination condition of i < len(l)
, in the way you've written the code, because len(l)
is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:
i = 0
while i < len(l):
if l[i] == 0:
l.pop(i)
else:
i += 1
(Python) List index out of range - iteration
You're modifying the list you're iterating over. If you do that, the size of the list shrinks, so eventually lst[i]
will point beyond the list's boundaries.
>>> lst = [1,2,3]
>>> lst[2]
3
>>> lst.remove(1)
>>> lst[1]
3
>>> lst[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
It's safer to construct a new list:
return [item for item in lst if item[0]!=1 and item[1]!=1]
IndexError: list index out of range in very simple 3 lines of Python code
It's not clear what exactly you're trying to do. When you iterate over an iterable like a list with
for i in my_list:
each i
is each member of the list, not the index of the member of the list. So, in your case, if you want to print each member of the list, use
for i in my_list:
print(i)
Think about it: what if the 3rd member of the list was 9
, for example? Your code would be trying to print my_list[9]
, which doesn't exist.
How to Fix List Index out of range in python?
You may try this instead:
def getMoneySpent(keyboards, drives, b):
q = []
for k in keyboards :
for d in drives :
price = k + d
if price <= b :
q.append(price)
return max(q) if q else -1
Instead of removing elements, just don't add them in the first place...
Unexpected error: IndexError: list index out of range when trying to access a list within a function
You pass empty list : myMax([])
to the function and you point to the first element of this empty list L[0]
. You need to check if the list L
is not empty.
Adding the below as the first lines of the function will help you to protect against None or empty list
if L is None or len(L) == 0:
raise ValueError('Input list can not be None or empty')
Why do I get List index out of range when trying to add consecutive numbers in a list using for i in list?
In your
for
loop, you're iterating through the elements of a lista
. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
Imagine if the lista
would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the lista
, which obviously is not there. This will give you anIndexError
.We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
and access the
a
's items like that:a[i]
. This won't give any errors.In the loop's body, you're indexing not only
a[i]
, but alsoa[i+1]
. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get anIndexError
. Why? Becauserange(5)
is essentially0 1 2 3 4
, so when the loop reaches 4, you will attempt to get thea[5]
item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting thea[5]
would mean getting the sixth element which does not exist.To fix that, you should subtract 1 from
len(a)
in order to get a range sequence0 1 2 3
. Since you're using an indexi+1
, you'll still get the last element, but this way you will avoid the error.There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
Python 3 : IndexError: list index out of range
When you start to remove items from a list, it changes in size. So, the i
th index may no longer exist after certain removals:
>>> x = ['a', 'b', 'c', 'd', 'e']
>>> x[4]
'e'
>>> x.pop()
'e'
>>> x[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
A simpler way to remove duplicate items is to convert your list to a set
, which can only contain unique items. If you must have it as a list, you can convert it back to a list: list(set(X))
. However, order is not preserved here.
If you want to remove consecutive duplicates, consider using a new array to store items that are not duplicates:
unique_x = []
for i in range(len(x) - 1):
if x[i] != x[i+1]:
unique_x.append(x[i])
unique_x.append(x[-1])
Note that our range bound is len(x) - 1
because otherwise, we would exceed the array bounds when using x[i+1]
.
Related Topics
Python Requests. 403 Forbidden
How Is the 'Is' Keyword Implemented in Python
When Does Python Allocate New Memory for Identical Strings
How to Define a Threshold Value to Detect Only Green Colour Objects in an Image with Python Opencv
"Getaddrinfo Failed", What Does That Mean
Caesar Cipher Function in Python
Python: Calling 'List' on a Map Object Twice
Pygame Already Installed; However, Python Terminal Says "No Module Named 'Pygame' " (Ubuntu 20.04.1)
How to Use Subprocess Popen Python
Way to Change Google Chrome User Agent in Selenium
Unnest (Explode) a Pandas Series
Prevent Sleep Mode Python (Wakelock on Python)
Python: Get a Frequency Count Based on Two Columns (Variables) in Pandas Dataframe Some Row Appers