Error in line 8

line 8 index error
https://www.codechef.com/viewsolution/28395527

and what the hell is this thread supposed to be?

2 Likes

It’s the exciting sequel (pardon the pun :)) to this thread!

3 Likes

list.pop(index) ----> removes the element from the list at given index and returns it.

You are popping out the elements inside a for loop.
Unlike other languages in Python the for loop works quite differently. The for loop in line 7, for i in range(0,len(l1)) will run exactly the number of times initially the length of l1. It doesn’t matter if you change the length. Once the condition is specified for “for loop” it cannot be changed in between.

This all might have been bounced off your head :joy: so let me explain with an example.

Suppose the length of l1 initially be 10, and let the list be [1,2,3,4,5,6,7,8,9,10], then the loop will run exactly 10 times no matter if you reduce the length inside the for loop (popping elements will reduce length)

So at line 8, when you are popping the elements you are removing the elements from the list so the list becomes shorter after each iteration. Suppose you have popped few elements and now the list is somewhat like [1,2,3,4,5,6,7] having 7 elements. Now suppose you do l1.pop(8). You don’t have index 8 in your list but the for loop will be still running, so it will give ListIndex out of range exception. Because you will be accessing elements out of the range of the list.

Suggestion : Try using while loop instead of for loop. :slightly_smiling_face:

1 Like

thanks a lot