Python: How efficiently remove items from list in for loop ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python: How efficiently remove items from list in for loop ?

The code __________________ for Object in List: if Condition: DoSomething(Object) List.remove(Object) ____________________ By this code, the loop will miss some of the Objects because of preddecessor removal. Please suggest better way. By efficiently i mean: - just one loop - no unneccesary copies of List (since it can be very large)

3rd Jan 2017, 10:34 AM
Michal Dohnal
Michal Dohnal - avatar
1 Answer
+ 5
In case the order of processing does not matter, a solution could be achieved by two code changes: 1. The list needs to be traversed in reversed order so that references to unprocessed list items are not changed by the deletion of the processed list items. 2. The remove() method will remove the first occurrence of Object which might be a problem if duplicates exist in the list. It is better to delete the list item with explicit index. It should be faster too. New code: __________________ for Index in range(len(List)-1, -1, -1): Object = List[Index] if Condition: DoSomething(Object) del List[Index] ____________________ Hope this helps!
3rd Jan 2017, 6:23 PM
Free Boro
Free Boro - avatar