Sundhar V Sundhar V - 3 years ago 93
Python Question

Removing an element from a list using for loop

Consider this snippet

k=[0, 5, 12, 94]

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

for a in k:

I expected the answer will be


But the answer displayed is


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download