Sundhar V Sundhar V - 1 month ago 6
Python Question

Removing an element from a list using for loop

Consider this snippet

k=[0, 5, 12, 94]
a=max(k)


I intend to delete the largest element for the list using for loop.

for a in k:
k.remove(a)


I expected the answer will be

[0,5,12]


But the answer displayed is

[5,12]


Am I missing something? It works fine with while loop.

Answer

If you're looking to create a new list where the maximum value has been eliminated completely, use a list-comprehension that selects the elements not equal to a = max(k).

That is:

k = [0, 1, 6, 6, 6]
a = max(k)

result = [i for i in k if i != a]

This results in a list containing:

[0, 1]

As an aside, you should know that assigning the name a inside the for clause of the loop is masking the a you defined with a = max(k).

As a result, the for loop is just trying to remove all elements from the list.