+ 1

Can any one explain me why there is list index out of range error in this code

def remove_odd(list1): for index in range(len(list1)): if list1[index]%2==0: list1.remove(list1[index]) list1=[1,2,3,4,5] remove_odd(list1) print(list1)

22nd Jan 2022, 4:59 AM
Sahil Jadhav
3 Answers
+ 4
Because you are working with len(original) from a list that you are already deleting elements from. I think that's it. I just noticed that also, you would be deleting the even ones, not the odd ones haha Maybe this can help you: i=0 while i<=len(arr): if arr[i]%2!=0: del arr[i] i+=1
22nd Jan 2022, 5:08 AM
CGM
CGM - avatar
+ 2
Thanks for anwers and thanks Cristian Gabriel for your explanation i completely understand it
22nd Jan 2022, 5:32 AM
Sahil Jadhav
0
Instead of removing items from the original `list` you have an option to filter the `list` instead. You can use filter() function or `list` comprehension to do this 👍 P.S. I think the function name 'remove_odd()' doesn't match what it does. The condition in the loop appears to be targeting even numbers instead of the odd ones : ) Also, as a future reference, use appropriate tags https://code.sololearn.com/W3uiji9X28C1/?ref=app
22nd Jan 2022, 5:23 AM
Ipang