0

I am trying to completely empty the list one by one but there are always 2 integers left. Is it possible to do it without it leaving the 2 highest value integers ? If so how ?

list = [1,2,3,4,5]
print (list)
for x in list:
    while x in list:
        list.remove(min(list))


print(list)
Marek Tran
  • 23
  • 5
  • If you want to empty a list by using `for` loop, you should do it the reverse way. Check [this](http://stackoverflow.com/questions/35618307/how-to-transform-string-into-dict/35618686#35618686) Otherwise, your indexer will reach the end of the list before getting through all your items. Doing it forward way will remove an item in the list as the indexer moves forward. It may disturb the iteration flow. That being said, using for loop is not the only way to empty a list – Ian Mar 24 '16 at 14:14

4 Answers4

0

There is an other way to empty a list. This way you don't need to use the for loop.

>>> lst = [1,2,3,4,5]
>>> del lst[:]
>>> lst
[]
>>> 

Or:

>>> lst = [1,2,3,4,5]
>>> lst[:] = []
>>> lst
[]
>>>

If you really want to empty the list one element at the time, which doesn't make much sense, you can use a while loop.

lst = [1,2,3,4,5]
x = len(lst)-1
c = 0
while c < x:
    for i in lst:
        lst.remove(i)
    c = c+1
print (lst)
>>> 
[]
>>>
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
0

I have a feeling there may be more to your question but to empty a list you can clear it using python3:

lst = [1,2,3,4,5]
lst.clear()

If you actually want each min and have to go one by one keep going until the list is empty:

lst = [1, 2, 3, 4, 5]

while lst:
    i = min(lst)
    lst.remove(i)
    print(i, lst)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

If you want to repeatedly remove the smallest element in this list and process it somehow, instead of just clearing the list, you can do this:

while list:  # short way of saying 'while the list is not empty'
    value = min(list)
    process(value)
    list.remove(value)

(this isn't the most efficient code as it iterates once to find the minimum and again to remove it, but it demonstrates the idea)

Your problem is that you're using a for loop on a list while modifying it which is bound to lead to problems, but there's really no need for a for loop at all.

Also don't use list as a variable name because it shadows the built-in name which is very useful for other purposes.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

I think this is what you are trying to do:

lst = [1,2,3,4,5] 
while lst:          # while the list is not empty
   m = min(lst)
   while m in lst: # remove smallest element (multiple times if it occurs more than once)
       lst.remove(m)
sapensadler
  • 386
  • 5
  • 11