1

I'm trying to iterate over a list of number and removing the values that are lower than a number that I use to compare.

My problem is that there's a number that is lower than the value that I use but it doesnt get removed.

I'm using the remove() function of the list but I don't know why it doesn't get removed

Here is my code:

def remove_lower_numbers(array_numbers, bigger_number):
    for elem in array_numbers:
        if elem <= bigger_number:
            array_numbers.remove(elem)
    print(array_numbers)

It works if I used a list comprehension like this:

array_numbers = [x for x in array_numbers if x >= bigger_number]

but I want to do it the way I firts mentioned for learning purposes

I call the function like this:

cards_array = [3, 2, 7]
remove_lower_numbers(cards_array, 8)

but the function prints:

[2]

and 2 is lower than 8 it should return None or a empty list.

TorkB80
  • 69
  • 1
  • 6
  • Interesting. What happens if you use `for elem in reversed(array_numbers):` instead? – wim Nov 05 '18 at 23:15
  • 1
    This is a duplicate for sure. You are changing the list you iterate. Don't do that. – progmatico Nov 05 '18 at 23:24
  • @wim: Even if it works, it's a bad idea to depend on it; mutating an iterable while iterating it is unsupported, so if it fails, you have no one to blame but yourself. – ShadowRanger Nov 06 '18 at 01:32
  • @ShadowRanger I did not say it was a good idea or that it worked. And the statement that *mutating an iterable while iterating it is unsupported* is incorrect. [List iterators are dynamically updatable](https://github.com/python/cpython/blob/v3.7.1/Lib/test/test_iterlen.py#L21-L30). – wim Nov 06 '18 at 01:50

1 Answers1

1

Using filter, which keeps only the values that return True for the lambda function:

list(filter(lambda x: x > 3, [1, 2, 3, 4, 5, 2, 3]))

Output:

[4, 5]
  • If you need a `lambda` to use `map`/`filter`, don't. Just use a listcomp or genexpr; they'll be faster and clearer than the `map`/`filter` equivalent (because they avoid the function call overhead entirely). The only time `map`/`filter` can win (at least on the CPython reference interpreter) is if the callback function is a built-in implemented in C. – ShadowRanger Nov 06 '18 at 01:30