-1

I'm doing an exercise where a function takes a list and an integer n and deletes every element if its index i satisfies (i+1)%n==0. Here's what I've come up with:

def f(lst, n):
    for i in range(len(lst)):
        if (i+1)%n==0:  
            del lst[i]

However, it gives me this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pop.py", line 4, in f
    del lst[i]
IndexError: list assignment index out of range

The index pointer i doesn't seem to be able to run out of range? What causes this to happen?

Taku
  • 31,927
  • 11
  • 74
  • 85
Christian Temple
  • 121
  • 1
  • 1
  • 7

2 Answers2

2

What data set are you using? Depending on the numbers in your data set, the problem is that you're deleting objects from your list, creating a conflict when you ask for a specific index in that list.

ex_list = [2, 5, 12]
print range(len(ex_list))

output [0, 1, 2]

So lets say the first item doesn't pass your test and gets deleted. Now oyur list looks like this:

ex_list
>>>[5, 12]

The problem is that your next i in your for loop will be 1 but now:

ex_list[1]
>>>12

and ultimately:

ex_list[2]
>>>IndexError: list assignment index out of range
1

What is happening is that when you are deleting an element from a list, your list size is changing.

You don't have to iterate over the list to find the the indexes that is divisible by n.
for e.g. if list_length = 8 and n = 2, then we know the element#[2,4,6,8] = index[1,3,5,7] have to deleted. You can just create a filter here or list comprehension like this will also do-

new_list = [old_list[i] for i in range(len(old_list_length)) if (i+1) % n == 0]
old_list = new_list

Note :- You can note iterate over a list, where a element have been deleted, since the original element you like to delete, will now have different index. Going with the example in the start of answer:- lets say you have deleted element#2(index = 1), Now subsequent element#4,#8 will now become element #3, #7, so now you cannot track the original elements you wanted to remove the list.

Muku
  • 538
  • 4
  • 18