By Finger twist


2011-06-07 02:29:26 8 Comments

I've got this piece of code :

numbers = range(1, 50)

for i in numbers:
    if i < 20:
        numbers.remove(i)

print(numbers)

but the result I'm getting is:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]

Of course I'm expecting the numbers below 20 to not appear in the results, I'm assuming I'm doing something wrong with the remove.

4 comments

@Trufa 2011-06-07 03:48:51

@senderle's answer is the way to go!

Having said that to further illustrate even a bit more your problem, if you think about it, you will always want to remove the index 0 twenty times:

[1,2,3,4,5............50]
 ^
[2,3,4,5............50]
 ^
[3,4,5............50]
 ^

So you could actually go with something like this:

aList = range(50)
i = 0
while i < 20:
    aList.pop(0)
    i += 1

print aList #[21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]

I hope it helps.


The ones below are not bad practices AFAIK.

EDIT (Some more):

lis = range(50)
lis = lis[20:]

Will do the job also.

EDIT2 (I'm bored):

functional = filter(lambda x: x> 20, range(50))

@Dr. belisarius 2011-06-07 04:34:09

@eyquem 2012-01-06 02:01:41

Removing items from a list is simple: begin at the list's end:

li = range(1,15)
print li,'\n'

for i in xrange(len(li)-1,-1,-1):
    if li[i] < 6:
        del li[i]

print li

result

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

[6, 7, 8, 9, 10, 11, 12, 13, 14]

@g.d.d.c 2011-06-07 04:29:20

I really like the answer @senderle provided. The only thing I want to add (I'd have commented, but can't get proper code formatting) is that you can also get away with side processing for your list comprehensions if you declare your functions ahead of time like so:

def checkRemoval(item):
  # some processing here
  return passed_inspection # Should be True / False.

newList = [item for item in oldList if checkRemoval(item)]

@senderle 2011-06-07 04:40:13

+1, interesting solution, and although some people might not agree with me, it seems to fall just barely on the correct side of this stricture, since you aren't using it for just side-effects.

@asmeurer 2011-06-07 06:07:01

If you do that, then it's cleaner to just use filter, like filter(checkremoval, oldlist).

@senderle 2011-06-07 02:31:40

You're modifying the list while you iterate over it. That means that the first time through the loop, i == 1, so 1 is removed from the list. Then the for loop goes to the second item in the list, which is not 2, but 3! Then that's removed from the list, and then the for loop goes on to the third item in the list, which is now 5. And so on. Perhaps it's easier to visualize like so, with a ^ pointing to the value of i:

[1, 2, 3, 4, 5, 6...]
 ^

That's the state of the list initially; then 1 is removed and the loop goes to the second item in the list:

[2, 3, 4, 5, 6...]
    ^
[2, 4, 5, 6...]
       ^

And so on.

There's no good way to alter a list's length while iterating over it. The best you can do is something like this:

numbers = [n for n in numbers if n >= 20]

or this, for in-place alteration (the thing in parens is a generator expression, which is implicitly converted into a tuple before slice-assignment):

numbers[:] = (n for in in numbers if n >= 20)

If you want to perform an operation on n before removing it, one trick you could try is this:

for i, n in enumerate(numbers):
    if n < 20 :
        print "do something" 
        numbers[i] = None
numbers = [n for n in numbers if n is not None]

Related Questions

Sponsored Content

32 Answered Questions

[SOLVED] "Least Astonishment" and the Mutable Default Argument

29 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3154354 View
  • 2598 Score
  • 29 Answer
  • Tags:   python list

23 Answered Questions

[SOLVED] How to remove items from a list while iterating?

  • 2009-07-30 15:36:42
  • lfaraone
  • 384896 View
  • 807 Score
  • 23 Answer
  • Tags:   python iteration

44 Answered Questions

[SOLVED] Removing duplicates in lists

19 Answered Questions

[SOLVED] How do I remove an element from a list by index in Python?

  • 2009-03-09 18:16:11
  • Joan Venge
  • 2132996 View
  • 1202 Score
  • 19 Answer
  • Tags:   python list

16 Answered Questions

[SOLVED] Convert bytes to a string?

22 Answered Questions

[SOLVED] How can I count the occurrences of a list item?

  • 2010-04-08 13:30:00
  • weakish
  • 1297778 View
  • 1258 Score
  • 22 Answer
  • Tags:   python list count

14 Answered Questions

[SOLVED] How to randomly select an item from a list?

  • 2008-11-20 18:42:21
  • Ray Vega
  • 1202109 View
  • 1506 Score
  • 14 Answer
  • Tags:   python list random

10 Answered Questions

9 Answered Questions

[SOLVED] How to remove the first Item from a list?

  • 2010-12-13 07:38:38
  • rectangletangle
  • 723365 View
  • 606 Score
  • 9 Answer
  • Tags:   python arrays list

Sponsored Content