IndexError when iterating a list and deleting item from a DIFFERENT list

Question:

Say I want to remove the number 4 from myList, I iterate through the list and if its equal to 4, I delete the item from a tempList which is not being iterated through. For some reason this still causes an IndexError even though it isn’t iterating the same list.

myList = [1,2,3,4,5,6,7,8,9]
tempList = myList

# Goes through each item and if it is 4, then it deletes it from the tempList
for i in range(9):
    if myList[i] == 4:
        del tempList[i]
Traceback (most recent call last):
  File ***, line 5, in <module>
    if myList[i] == 4:
IndexError: list index out of range

My only idea is that somehow by deleting an item in tempList, it also does so in myList as well – somehow they are linked. If so, how do I make tempList not ‘linked’ to myList .

Asked By: hjw

||

Answers:

Hello you can create a real copy of myList and change the looping range 😉 :

myList = [1,2,3,4,5,6,7,8,9]
tempList = myList.copy()

# Goes through each item and if it is 4, then it deletes it from the tempList
for i in range(len(myList)):
    if myList[i] == 4:
        del tempList[i]
Answered By: rafidini
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.