0
list1=[1,2,3,2,2,1,1,1,1]
for i in list1:
    if(i==min(list1)):
        list1.remove(i)
print(list1)

ABOVE IS THE CODE WHICH IS WRITTEN IN A PYTHON TO SHOW MY PROBLEM .

As you can see in above code of python ,In a given list there is a 1 which is a minimum element in a list and it occurs 5 times in a list .I want a list in which all 1 should be absent ,So I used here a min function in a python to find a minimum element in a list and by using for loop I removed all minimum elements . But when I ran this code , output which was very unexpected to me was a list which still contains 1 .

sbottingota
  • 533
  • 1
  • 3
  • 18
  • The issue is that after removing the current value `for loop` jumps to the next index of the updated list, i.e. skips and doesn't check `the next one` value. – Aksen P Apr 09 '23 at 06:06

3 Answers3

2

Do not try to modify a list while iterating over it. This will cause problems. Consider what happens if we do this with your example list: [1, 2, 3, 2, 2, 1, 1, 1, 1].

The elements that are considered:

[1, 2, 3, 2, 2, 1, 1, 1, 1]
 ^

Because this is removed, we skip the 2.

[1, 2, 3, 2, 2, 1, 1, 1, 1]
       ^

[1, 2, 3, 2, 2, 1, 1, 1, 1]
          ^

[1, 2, 3, 2, 2, 1, 1, 1, 1]
             ^

[1, 2, 3, 2, 2, 1, 1, 1, 1]
                ^

[1, 2, 3, 2, 2, 1, 1, 1, 1]
                      ^

Every time we remove an element, we're not evaluating the next element on the next iteration. End result?

[2, 3, 2, 2, 1, 1]

The other danger is that you're modifying list, but each iteration recalculates min(list1). This value can change because you've removed elements from list. Your example list doesn't trigger this because there is always a 1 left at the end, but what if you test with something like: [1, 2, 3, 2, 2, 2]?

On the first iteration 1 is the minimum element, but on subsequent iterations, 2 is.

Instead build a new list with the elements you want. You can then assign it back to the same variable name.

list1 = [1, 2, 3, 2, 2, 1, 1, 1, 1]
m = min(list1)
list1 = [x for x in list1 if x != m]
Chris
  • 26,361
  • 5
  • 21
  • 42
0

You can use the next code snippet for that purpose:

list1 = [1, 2, 3, 2, 2, 1, 1, 1, 1]
min_element = min(list1)
new_list = [x for x in list1 if x != min_element]
print(new_list)
Aksen P
  • 4,564
  • 3
  • 14
  • 27
0

I think your problem is that you misunderstand your code. Instead you could use the following code:

old_list = [1, 2, 3, 2, 2, 1, 1, 1, 1]

min_value = min(old_list)
new_list = [x for x in old_list if x != min_value]

print(new_list)

which prints:

[2, 3, 2, 2]

The above code creates a new list with all of the elements of the old list except for those which are equal to min_value (i.e. all elements except for 1).


I hope this helps.

sbottingota
  • 533
  • 1
  • 3
  • 18