List Mutation Inside Iteration

Posted by Afsal on 08-Dec-2023

Hi Pythonistas!

Today we will discuss common mistakes that we get while reviewing the code. Which is modifying the list while iterating. This will cause bugs in our code. Because if you mutate the list this will cause a change in length so it can either skip some element or process an element more than once.

Let us consider the example we has list of numbers and want to return the even numbers only, Let us check this with mutation

Code

import random

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

random.shuffle(a)

for i in a:
    if i% 2 != 0:
        a.remove(i)

print(a)

Output

[3, 4, 8, 6, 2, 10]

Here we can see that the list contains odd numbers also, but there is no issue with logic, but the index of the element shifts while removing the item from a list. So sometime the some index will not be processed

Solution

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even = []

for i in a:
    if i%2 == 0:
        even.append(i)

print(even)

Output

[2, 4, 6, 8, 10]

 Pythonics solution

even = [i for i in a if i% 2 == 0 ]

print(even)

Output

[2, 4, 6, 8, 10]

I hope you have learned something from this post. If you are seeing common problems like this please share with parseltongue.co.in so that everyone can learn. You can connect us at afsal@parseltongue.co.in