this is my code :
a=[1,0,None,3]
def b(my_list):
for i in range(len(my_list)):
if not my_list[i]:
a.remove(my_list[i])
else:
do_something()
return my_list
a = b(a)
print a
and the error is :
Traceback (most recent call last):
File "c.py", line 18, in <module>
a = b(a)
File "c.py", line 12, in b
if not my_list[i]:
IndexError: list index out of range
so what can i do ,
thanks
You are modifying the same list that you’re iterating over, inside your loop. You can fix this by making a copy of the list and returning that:
Normally in Python, when you call a function such as
b(a), then insideb, the parametermy_listis a reference to the same list as was passed in (a). The statementnew_list = my_list[:]makes a copy of the list that you can modify and return inside the function.