Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python remove during iteration

#removing during iteration is terrible since if you remove an element at index i,
#you shift every element 1 index to the left so you skip the next element's index
#which becomes the current one you are on

#ex of this problem
list = [0, 3, 3, 4, 3]

for i in list:
    if i == 3:
        list.remove(i)
print(list)
 #OUTPUT: [0, 3, 4] #THERE IS STILL ONE '3' left because it skipped it
  
  
  
#FIXED EXAMPLE

list = [0, 3, 3, 4, 3]

for i, element in sorted(enumerate(list), reverse=True):
    if element == 3:
      list.pop(i)#you can also use remove in certain cases
print(list)

#OUTPUT: [0, 4] #It didnt skip the 3s since it sorted the list from L to G and
                #reversed it [4, 3, 3, 3, 0] grouping the 3s together and since
                #it got the index and value of the element it removed the wanted
                #indices
 
PREVIOUS NEXT
Tagged: #python #remove #iteration
ADD COMMENT
Topic
Name
7+5 =