saspy
saspy

Reputation: 29

For loop resulting in wrong output

The code snippet below results in [5,7,18,23,50], why 5 is not getting removed from the resultant list?

list1 = [11, 5, 17, 18, 23, 50]  
not_needed = {11, 5}

for e in list1:
    if e in not_needed:
        list1.remove(e)
    else:
        pass

print(list1)

Upvotes: 0

Views: 82

Answers (5)

abhishek
abhishek

Reputation: 83

for loop in python runs on the indexes not on each element.

When it finds 11 and removes it from list1, list1 becomes [5, 17, 18, 23, 50] but the loop is now on second element. So it misses 5 in the list.

Upvotes: 1

Matt Moore
Matt Moore

Reputation: 2775

Use list comprehension when looping over a list and modifying it at the same time.

list1 = [x for x in list1 if not x in not_needed]
list1
[17, 18, 23, 50]

Further details on this here: https://www.analyticsvidhya.com/blog/2016/01/python-tutorial-list-comprehension-examples/

Upvotes: 2

r_batra
r_batra

Reputation: 410

This is because after first iteration item 11 is deleted and it goes for second index which becomes 17 in list [5,17,18,23,50] The best way to rectify this is to take result list so that you dont have to mutate "list1"

list1 = [11, 5, 17, 18, 23, 50]
not_needed = {11, 5}
result = []
for e in list1:
    if e in not_needed:
        pass
    else:
        result.append(e)

print(result)

Upvotes: 1

rdas
rdas

Reputation: 21275

Because once the 11 is removed, the 5 gets skipped during iteration. This is why you never iterate over a list and remove from it at the same time.

list1 = [11, 5, 17, 18, 23, 50]
not_needed = {11, 5}

for e in not_needed:
    list1.remove(e)

print(list1)

Gives:

[17, 18, 23, 50]

Upvotes: 2

nosklo
nosklo

Reputation: 222842

Because you are modifying the list as it is being iterated over.

  • When you read the first item, it is 11 so it gets removed.

  • When you read the second item, it is 17, because the first item was removed. The item 5 is now the new first item and you never get to check it.

Upvotes: 4

Related Questions