-1

I tried the following code:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for x in arr:
  if x > 3:
    arr.remove(x)

print(arr)

It gives the following output:

[1, 2, 3, 5, 7, 9]

While instead i thought it would remove from the array every element bigger than 3. Why is that? And how can i make it remove every element bigger than a certain amount?

San9096
  • 231
  • 4
  • 12

1 Answers1

4

Modifying a list that you're in the process of iterating over will frequently yield unexpected results. A better option is to create a new list:

arr = [x for x in arr if x <= 3]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Am i forced to create a new variable for that? I'm pretty new to Python, and i'm struggling to understand why does this happen – San9096 Jun 02 '20 at 13:47
  • There is no new variable created in that example; I'm reassigning `arr`, the variable name you already used. – Samwise Jun 02 '20 at 14:46
  • The thing the above code does differently from your `for` loop is that a completely new list is created by the comprehension expression on the right before being assigned to `arr`. The original `arr` list is never modified; we just generate a new list based on it, and then replace the entire thing. – Samwise Jun 02 '20 at 15:04
  • Got it, thank you! – San9096 Jun 02 '20 at 17:37