Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

PREVIOUS NEXT
Code Example
Python :: update windows wallpaper python 
Python :: Plotting keras model trainning history 
Python :: colored text python 
Python :: django.db.utils.OperationalError: no such table: 
Python :: python how to get every name in folder 
Python :: remove all of same value python list 
Python :: f string decimal places 
Python :: actual keystroke python 
Python :: number pyramid pattern in python 
Python :: leap year algorithm 
Python :: python no new line 
Python :: calculate root mean square error python 
Python :: How to normalize the data to get to the same range in python pandas 
Python :: reload is not defined python 3 
Python :: how to get the year in python 
Python :: select text in a div selenium python 
Python :: change text color docx-python 
Python :: python pdf to excel 
Python :: google translate with python 
Python :: simulated annealing python 
Python :: pygame.set_volume(2.0) max volume 
Python :: python define 2d table 
Python :: python initialize dictionary with lists 
Python :: pandas select data conditional 
Python :: convert categorical data type to int in pandas 
Python :: python nmap 
Python :: rename a column in python 
Python :: how to record pyttsx3 file using python 
Python :: sklearn rmse 
Python :: colab read xlsx 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =