Skip to main content

Mistake in List Iteration

·169 words·1 min
Posts 101 python
Table of Contents
Never ever modify your list while iterating through the list.

This post is taking from Indently’s shorts at https://www.youtube.com/shorts/X8KL7iAk-7k.

List Item Removal
#

Suppose we want to remove an item within a list. Such as ‘B’.

And below is one of the common mistakes that junior developer makes. It uses for-loop to remove the item while iterating through the list.

But the result shows an unexpected behavior here. See the code below.

items1 = ['A', 'B', 'C', 'D', 'E']
items2 = []

for item in items1:
    if item == 'B':
        items1.remove('B')
    else:
        items2.append(item)

print(items2)
# ['A', 'D', 'E']

Supposed we are expecting the result to be ['A', 'C', 'D', 'E']. If you want to modify the original list, simply create another list.

And below here is the correct way.

items1 = ['A', 'B', 'C', 'D', 'E']
items2 = [ item for item in items1 if item != 'B' ]
print(items2)
# ['A', 'C', 'D', 'E']

Links#

Indently’s YT video at 10 Nooby Mistakes Devs Often Make In Python:

Related

MkDocs (Python)
·182 words·1 min
zd
Posts 101 documentation markdown python tools
Documenting project with MkDocs.
Generator Expression in Python
·567 words·3 mins
Posts 101 python
Python: List comprehension vs Generator expression.
Module vs Package vs Library
·53 words·1 min
Posts 101 python
Quick differences among a module, a package, and libary in Python.