0

I have the following python code:

raw_list = reminders_context['data']['reminder_list']

This statement works fine and gets the required info that I want.

The following code gives me the error list index out of range but the inner workings of the for loop for eg.[I obviously substitute the 'i' value for a number, then get the first 10 characters of the list item with [:10]], work fine when I set a trace in pdb mode.

raw_list[i]['created'][:10] == raw_list[i + 1]['created'][:10]

Code that gives an error:

for i in range(len(raw_list)):
    if raw_list[i]['created'][:10] == raw_list[i + 1]['created'][:10]:
        del raw_list[i + 1]
    else:
        pass

How can I change it so that I do not get the error?

I have seen something about how my list gets reduced in the for loop when iterating but I simply do not know how to implement it in my code.

The article I'm referring to is here:

python : list index out of range error

Community
  • 1
  • 1
AKaY
  • 17
  • 6
  • possible duplicate of [Remove items from a list while iterating in Python](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) – SiHa Jul 23 '15 at 12:17

2 Answers2

0

How about changing:

for i in range(len(raw_list)):

into:

for i in range(len(raw_list)-1):
wmoco_6725
  • 2,759
  • 1
  • 12
  • 12
0

range(n) goes from 0 to n-1. In this case, n-1 is the last valid index in your list. When your loop is on the iteration i = len(raw_list)-1 (the last iteration), your operation to access the i+1th element tries to access len(raw_list) which is not a valid index in the array. So the last valid iteration your loop can do is i=len(rawlist)-2

Basically, you need to make your for loop do one less iteration.