0

I want to transfer every element from one list to another with ascending order. This is my code:

l=[10,1,2,3,4,5,6,7,8,9]  
p=[]  
for x in l :   
    p.append(min(l))  
    l.remove(min(l))  
print p
print l

But it returns this result:

[1, 2, 3, 4, 5]
[10, 6, 7, 8, 9]

I don't know why it stop at half way, please help me on it...Thanks!

Light
  • 61
  • 1
  • 4

4 Answers4

7

Just do this:

p = sorted(l)
#l = [] if you /really/ want it to be empty after the operation

The reason you're getting wonky behavior is that you're changing the size of the sequence l as you iterate over it, leading you to skip elements.

If you wanted to fix your method, you would do:

for x in l[:]: 

l[:] creates a copy of l, which you can safely iterate over while you do things to the original l.

roippi
  • 25,533
  • 4
  • 48
  • 73
  • 1
    This is the easiest, most-Pythonic way. Not sure why everyone's complicating it. In addition, if you don't want to assume that `p` is empty, and want to append the sorted elements of `l`, you can do `p += sorted(l)`. – Jim Stewart Nov 04 '13 at 04:15
1

try this:

p = []
while len(l) > 0:
  p.append(min(l))
  l.remove(min(l))

Using while instead of for prevents you from modifying the list as you're iterating over it.

dave
  • 12,406
  • 10
  • 42
  • 59
  • I have to point out that this algorithm is `O(n**2)`, and an inefficient `O(n**2)` at that. At least save `min(l)` in a local so you don't compute it twice. – roippi Nov 04 '13 at 04:33
  • Sure, the answer was really meant to show the value of not modifying while iterating. The runtime is the same as OP's (if it worked as he/she intended). – dave Nov 04 '13 at 04:38
  • 1
    @dave I know, not a knock on you. Just a note to the OP, though he's probably not *incredibly* concerned about time complexity. – roippi Nov 04 '13 at 04:54
0

If you want to retain the original unsorted array, use a copy of l.

Check out this answer for more information. https://stackoverflow.com/a/1352908/1418255

Community
  • 1
  • 1
Ryan Jackman
  • 780
  • 2
  • 8
  • 24
0

Gee, I hope your lists are short. Otherwise, all that min()'ing will yield a slow piece of code.

If your lists are long, you might try a heap (EG heapq, in the standard library) or tree (EG: https://pypi.python.org/pypi/red-black-tree-mod) or treap (EG: https://pypi.python.org/pypi/treap/).

For what you're doing, I'm guessing a heapq would be nice, unless there's a part of your story you've left out, like needing to be able to access arbitrary values and not just the min repeatedly.

dstromberg
  • 6,954
  • 1
  • 26
  • 27