# (FAQ) Removing elements while iterating over a collection

### A:

Many programming newcomers try to do something like the following:

and are surprised to find that some elements that should be removed are not.

To understand why this happens, imagine that we want to remove all bs from the list [a, b, b, c] while looping over it as in the pseudocode above. It’ll look something like this:

+-----------------------+
|  a  |  b  |  b  |  c  |
+-----------------------+
^ (first iteration)

+-----------------------+
|  a  |  b  |  b  |  c  |
+-----------------------+
^ (next iteration: we found a 'b' -- remove it)

+-----------------------+
|  a  |     |  b  |  c  |
+-----------------------+
^ (removed b)

+-----------------+
|  a  |  b  |  c  |
+-----------------+
^ (shift subsequent elements down to fill vacancy)

+-----------------+
|  a  |  b  |  c  |
+-----------------+
^ (next iteration)


Notice that we skipped the second b! Once we removed the first b, elements were shifted down and our for-loop consequently failed to touch every element of the list.

This problem can be solved if we iterate over the list backwards:

+-----------------------+
|  a  |  b  |  b  |  c  |
+-----------------------+
^ (first iteration)

+-----------------------+
|  a  |  b  |  b  |  c  |
+-----------------------+
^ (next iteration: we found a 'b' -- remove it)

+-----------------------+
|  a  |  b  |     |  c  |
+-----------------------+
^ (removed b)

+-----------------+
|  a  |  b  |  c  |
+-----------------+
^ (shift subsequent elements down to fill vacancy)

+-----------------+
|  a  |  b  |  c  |
+-----------------+
^ (next iteration)

etc.


Since removing an element results in subsequent elements being shifted down as opposed to previous elements being shifted up, iterating in reverse order circumvents the skipping issue.

However, there are generally better approaches than iterating backwards. For example, in Java, the appropriate method would be to use an Iterator as returned by the iterator method of Collection and to call remove on it:

In Python, the appropriate method would be to use a list comprehension:

or, possibly, the built-in function filter().