1

I have a mixed nested list [[name1,score],[name2,score],...]. How do I remove the names with the lowest score? I selected an element with the lowest score and looped through the list and compared scores and remove if the score matches the min.

lmin=min(list, key = lambda x: x[1])
for l in list:
    if( ls[1] == lmin1[1]):
        ls1.remove(l)

But it doesn't remove all, only the first instance. Where am I making a mistake? Best,

Mikhail Zhuikov
  • 1,213
  • 2
  • 9
  • 19
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – DarrylG Nov 17 '20 at 10:16

2 Answers2

1

This is a better way to filter:

lmin=min(list_, key = lambda x: x[1])
li = [ item for item in list_ if item[1] != lmin]

Note that you shouldnt use the word list as variable as it is a saved keyword...

adir abargil
  • 5,495
  • 3
  • 19
  • 29
0

You can do it with:

Mylist = [["name1",10],["name2",4],["name3",40]]
print(Mylist)
to_remove=min(Mylist, key = lambda x: x[1])
Mylist.remove(to_remove)
print(Mylist)

result:

[['name1', 10], ['name2', 4], ['name3', 40]]
[['name1', 10], ['name3', 40]]
Renaud
  • 2,709
  • 2
  • 9
  • 24