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)
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)
>>>
[]
>>>
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)
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.