2

I have a list of floats and I want to remove elements which are either greater than a certain number or less than a certain (different) number. This is the code that I have so far:

a = ['239.12835442230858', '22.756759356300982', '32.98715001831536', '460.11899977144816', '747.5029387021966', '25.97292253382583', '150.94457242947556', '197.14098031753895', '394.44390781374057', '320.11301380981826', '138.66237294322895', '87.7095435481745', '427.8799219223041', '445.9006435386053', '62.716459379313704', '259.19872485615906', '212.75590521862267', '455.3882240904654', '259.07638854400676', '425.90576134140446']
print type(a[0])
for i, val in enumerate(a):
    a[i] = float(val)

print type(a[0])

for i in a:
    if i < 30 or i > 200:
        a.remove(i)

But this doesn't work as I expected it to. When I visualize this code here: http://www.pythontutor.com/visualize.html, it seems to be skipping the elements that come after an element that is removed. I see no reason why this would be the case with my code.

P.S. I am aware that I can do what I'm trying to do using np.where, but I want to know why my current code does not work.

  • 1
    I would be interested to see an answer to the exact question asked, not code that gives the desired output. Why do some elements get skipped when performing this method? – d_kennetz Oct 04 '18 at 03:40
  • 1
    @d_kennetz: List iterators are index based. If you remove an element while iterating, the next value is shifted down to the current index, then the iterator advances the index to the next item, skipping the item that was just shifted down. I swear this question has been asked a dozen times already (just added four duplicates, there are *many* more). – ShadowRanger Oct 04 '18 at 03:44
  • Haha shadow shutting it down! – d_kennetz Oct 04 '18 at 03:50

1 Answers1

2

You're modifying the list as you're iterating over it. Do a list comprehension instead:

[i for i in a if not (i < 30 or i > 200)]
Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52