0

Given a list of integers how would I remove all values greater than a given value, it seems to work with all values except for one. I know this is an issue probably an issue of changing the length of the list while I'm iterating through it but I just cant figure out where the issue is.

nums = [100,2,7,11,13,15]
target = 9


for x in nums:
    if x > target:
        nums.remove(x)

print(nums)

Returns:

[2, 7, 13]

Why not

[2, 7]
  • Don't change the list you are iterating over! (search for that, with "Python" added, and you'll get numerous explanations. Your question is a duplicate somewhere here on StackOverflow.) – 9769953 Dec 01 '22 at 20:34
  • `nums[:] = [i for i in nums if i <= target]` ? – S.B Dec 01 '22 at 20:35
  • 1
    Classic solution: `nums[:] = [i for i in nums if i <= target]` The issue in your solution is the removal during iteration as you predicted. When the `for` loop goes to index 3 (`11`) you remove index 3, and then it goes to index 4 which is originally index 5. – Bharel Dec 01 '22 at 20:35
  • 1
    @S.B, @Bharel `nums = [i for i in nums if i <= target]` is (much) more sensible. Just reassign the variable name. – 9769953 Dec 01 '22 at 20:36
  • 1
    @9769953 But it's now a new list object not *"your"* original list. IDs are different. So it depends on what is needed. – S.B Dec 01 '22 at 20:37
  • @S.B That doesn't matter here. The result is the same. You don't need the "original" list (i.e., pointing at the same memory address). The original list will simply be garbage collected. Arguably, the assignment even looks confusing: you assign to the full list (`[:]`), which is six elements large, but you're assigning to a new list that is two elements large. – 9769953 Dec 01 '22 at 20:40
  • @9769953 OP tried to remove elements from the list, maybe they need their original list, maybe it's in a function and the function is supposed to mutate the list! It's a closer match to their need. Confusing for who? the one who doesn't know Python? Are you saying that we should only use `[:]` assignment for exactly same number of items? – S.B Dec 01 '22 at 20:44
  • @S.B In this case, we only have what we see. You're making assumptions which are not validated, and something like "the function is supposed to mutate the list" seems very unlikely: otherwise the OP wouldn't ask this question in the first place! So yes, confusing for someone who knows little of Python, which I hazard a guess is the OP. – 9769953 Dec 01 '22 at 20:48

0 Answers0