My expected output is [(2,1),(3,0)]. But why this program gives index out of range error. Explain the reason | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

My expected output is [(2,1),(3,0)]. But why this program gives index out of range error. Explain the reason

z=[(3,0),0,(2,1)] for k in range(0,len(z)): if isinstance(z[k],int): del z[k] else: z=[z[k]] z.sort() print(z)

28th Feb 2019, 12:34 PM
Shaik Abeedh
Shaik Abeedh - avatar
2 Answers
+ 4
Modifying a list/removing elements from a list while you're iterating over it is usually not a good idea. The first element of the list is a tuple, not an integer, so the else statement is executed and z will be changed to a list that only contains its former first element ([z[k]]). With the next iteration you try to access the second element of the list which doesn't exist. Also, the last element of the list has the index len-1, so there's something wrong with the range definition too
28th Feb 2019, 12:45 PM
Anna
Anna - avatar
+ 2
I agree with Anna , Create a new list to append the instances you need rather than removing the ones you do not need. However, your range set is okay because range will go up to the length of the list but will not include it during the iteration and will not go past the index range.
28th Feb 2019, 12:59 PM
Nathan Lewis
Nathan Lewis - avatar