0

I'm trying to transfer items from one list to the other (like below) but the result is really puzzling. Does anyone have an idea what's going on here??

l1=range(1,11)
l2=[]
for i in l1:
    if i>=6:
        l2.append(i)
        l1.remove(i)
print l1
print l2

l1 = [1-5, 7, 9] # and
l2 = [6, 8, 10]  # !!
jamylak
  • 128,818
  • 30
  • 231
  • 230
Sergio Da Silva
  • 341
  • 1
  • 3
  • 3
  • @minitech: this sounds sarcastic. Just because something is clear to you, it isn't clear to everyone. – Ned Batchelder Jul 21 '12 at 18:37
  • @NedBatchelder: It's not, I'm actually wondering what the expected result was. Just because it's sometimes possible to figure out the intention of the code based on the general tone doesn't mean it's necessarily the right one, and I don't want to waste time answering the wrong question. – Ry- Jul 21 '12 at 18:43

2 Answers2

3

The problem is due to the fact that you are modifying the list that you are iterating over.

If you search on SO, you'll find a number of posts regarding this. E.g., Modifying list while iterating, Python: Removing list element while iterating over list, etc

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
3

You shouldn't modify a list that you're iterating or you'll get weird results. It's like cutting the branch that you're sitting on. How about creating two lists based on l1 ?

big = [x for x in l1 if x >= 6]
small = [x for x in l1 if x < 6]

Better yet, if you care about performance:

big = []
small = []

for item in l1:
    if item >= 6:
        big.append(item)
    else:
        small.append(item)
Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • Even better: `big = range(6, 11)` and `small = range(1, 6)` ;) – Ry- Jul 21 '12 at 17:52
  • Guys, thank you all very much for your help!! I was completely unaware that I'm not allowed to edit lists over which I'm iterating. I'll just go with two lists then, no problem! – Sergio Da Silva Jul 22 '12 at 17:44