0

I want to be able to get a list with a range of numbers 3 or higher, and turn it into a list of numbers of range 1 to 3 only. The code only removes some numbers above 3 and leaves others. I want all numbers above 3 removed from the list.

thelist= [1,8,9,2,3]

for element in thelist:
    if int(element) >= 4:
        thelist.remove(element)
    elif int(element) <= 3:
        continue

print(thelist)   
# prints [1, 9, 2, 3]. Number 8 was removed but not number 9
steven-14
  • 1
  • 2
  • One simple way: `[x for x in thelist if x in [1,2,3]]`. Also, "a list with a range of numbers 3 or higher" doesn't seem to be your actual requirement. – jarmod Nov 03 '22 at 12:31
  • Or use filter: `list(filter(lambda x: x >= 1 and x <= 3, thelist))` – jarmod Nov 03 '22 at 12:36

2 Answers2

0

You don't need the else part, so you can delete it.

But your code is not working because you need to make a copy of the list first, you can read more here

Solution : add [:] after thelist in the for loop

thelist = [1,8,9,2,3]

for element in thelist[:]:
    if int(element) >= 4:
        thelist.remove(element)


print(thelist)   
msabic22
  • 333
  • 2
  • 9
0

Attempting to modify a list while iterating over it is going to result in different behavior than you're expecting.

In your example, if you remove 8, 9 now slots down into the spot 8 was in, and thus is skipped on the next iteration.

You want instead to create a new list containing just the values that meet your criteria. This is a good opportunity to use a list comprehension.

thelist = [x for x in thelist if x < 4]

Should you wish to check that each element is 1, 2, or 3:

thelist = [x for x in thelist if x in {1, 2, 3}]
Chris
  • 26,361
  • 5
  • 21
  • 42