-1

I encountered the following problem: I have a list of numbers and a maximal value. I want to exclude all values in num that are greater than the given max. I wrote two loops that should be able to do so:

num=[0.5,1,1.5,2]
max=0.5

for eachNum in num:
    if eachNum>max:
        num.remove(eachNum)

i=0
while i<len(num):
    if num[i]>max:
        num.pop(i)
    i=i+1

Both loops failed. They left the 1.5 in the list and I do not get why. Any help greatly appreciated.

lucloe
  • 3
  • 3
  • 2
    `num.pop(i)` It's a bad idea to mutate (change) an object as you are iterating through it. – Learning is a mess Feb 28 '19 at 16:13
  • try appending the elements that pass the criteria to a new list instead of removing ones that fail – SuperStew Feb 28 '19 at 16:14
  • dont modify your list while iterating it - simple as that. use list comp: `a = [x for x in [0.5,1.5,2] if x <= 0.5]` and keep what you want. – Patrick Artner Feb 28 '19 at 16:14
  • You should not edit the list while you iterate over it. When you do that, `item[2]` suddenly becomes `item[1]`, but you've already iterated past that index, so it skips – G. Anderson Feb 28 '19 at 16:14

1 Answers1

2

The loops are failing because you are changing the list while iterating over it.

A great way to accomplish this would be to use filter:

num=[0.5,1,1.5,2]
max=0.5
less_than_max = list(filter(lambda x: x < max, num))

Check out the python documentation for more info: http://book.pythontips.com/en/latest/map_filter.html

Sara Fuerst
  • 5,688
  • 8
  • 43
  • 86