An Unexpected Output of Python!!

Python is an amazing language, think of anything, you name it, Python has it!! From game development, web development to machine learning, deep learning, natural language processing, image processing, everything python can do. List just goes on!!

But there are certain unexpected outputs of python. Here, let’s talk about one of it.

Problem Statement

Say you are given a simple list, without any nesting. Assume the list is

l = [1,2,2,2,"sim","k",2,10+20j,True,2]

Remove all 2’s from the list and then print list.

Solution

Now there can be many possible solutions. One of them, which gives perfect result is given below.

for i in l:
while 2 in l:
l.remove(2)

This works absolutely fine. If I write

print(l)

The output is:

Google Colab solution for Problem Statement

This is absolutely fine, but, if we make a solution, as given below, you won’t get what’s expected.

for i in l:
if i == 2:
l.remove(2)

The output is:

Google Colab other solution for Problem Statement

See, the last 2 didn’t get deleted. Now code will work fine, if there are 2’s in the middle or at first place, but if 2 occurs at last position of list and you don’t have anything at last but only 2's, then you can’t remove it with this logic. Remove it with logic given above.

Let’s modify list and see if what is said, is right or not? Check the output below.

Output for modified list

Well, what is the reason? Try and explore!!

A spiritual & honest being | M.Tech. 1st-year student | Passionate about teaching, helping others, data & machine learning | Believes in VOLUNESIA.