May-15-2021, 01:49 PM
When iterating over a list. Then remove item from same list. Will cause next item to be skip in list.
Example. Try to remove 2 and 3. But 3 will never get check.
You can copy the list or you can create a list for deletion.
Example. Try to remove 2 and 3. But 3 will never get check.
mylist = [1, 2, 3, 4, 5] for i in mylist: print(i) if i in [2, 3]: mylist.remove(i) print(mylist)You have two options.
You can copy the list or you can create a list for deletion.
mylist = [1, 2, 3, 4, 5] removelist = [] for i in mylist: print(i) if i in [2, 3]: removelist.append(i) for r in removelist: mylist.remove(r) print(mylist)
mylist = [1, 2, 3, 4, 5] # shallow copy for i in mylist[:]: print(i) if i in [2, 3]: mylist.remove(i) print(mylist)
99 percent of computer problems exists between chair and keyboard.