I want to get a ordered list with ascending order, but leave out the first element in the original list. But the first for-loop only runs 4 times. After 4 times loop in first for-loop:
lst=[6, 5, 4]
I think the first for-loop should keep running, but it finishes. I don't know why?
Source code below:
#coding: utf-8
lst = [0, 1, 6, 2, 5, 3, 4]
new_lst = [] # the ordered list, [0, 1, 2, 3, 4, 5, 6]
p0 = lst[0] # the first element can be arbitrary
lst.remove(p0)
new_lst.append(p0)
for temp in lst:
lst.remove(temp)
while 1:
for pt in lst:
if temp < pt:
continue
else:
lst.append(temp)
temp = pt
lst.remove(pt)
break
else:
new_lst.append(temp)
break
print("the ordered list:", new_lst)
At last, I only get:
('the ordered list:', [0, 1, 2, 3])
[1, 2, 3, 4, 5, 6]?sorted? A lot simpler that way (new_lst = sorted(lst[1:])could replace it all). Either way, you can't safely mutate alistwhile iterating it.listwhile iterating it; in practice on CPython, it doesn't error out, but if you remove the item you're currently on, it ends up skipping the following item in the iteration. Click the link in this comment, and view the other linked questions from there; several of them are of the form "I calllist.removein a loop that iterates over thelistand it breaks, why?"