Python is a popular programming language that offers plenty of useful features, and is used by many software & web developers around the world. It also offers numerous data structures to store data. List is one of the most popular python data structures, which is very versatile. Sometimes you may need to remove item from list while iterating over it. There are a couple of ways to do this in Python. We will look at both these methods.
Python remove item from list while iterating over it
Here are the couple of ways to remove item from list while iterating over it – using remove function and using del keyword.
1. Using remove function
Here is an example to remove item with value ‘b’ from out list below.
>>> li=['a', 'b', 'c', 'd', 'e'] >>> for i in li: if i=='b': li.remove(i) >>> li ['a', 'c', 'd', 'e']
In the above code, we loop through our list, and check each item to see if its value is ‘b’. When we find the matching element, we use remove function to delete the element. Every list has a built-in function remove() that you can use to delete item.
2. Using del function
You can also use del keyword to delete a list item as shown below.
>>> li=['a', 'b', 'c', 'd', 'e'] >>> for i in range(len(li)-1,-1,-1): if li[i]=='b': del li[i] >>> li ['a', 'c', 'd', 'e']
In the above code, we iterate through the list items one by one, check if the item’s value matches out required value, ‘b’ and then use del keyword to delete the matching element.
That’s it. As you can see, it is very easy to remove List items during iterations. You can use either of these methods depending on your requirement.