Sorted List vs Unsorted List

Removing even numbers from a list using the modulo operator should be simple. if num % 2 == 0 then remove from the list. However, it works as expected only when the list is sorted using the sorted python function:

Blockquote
lst1 = [1, 2, 10, 4, 20, 5, 3, 21, 40]
for num in lst1:
if (num % 2) == 0:
lst1.remove(num)

print(lst1)
output: [1, 10, 20, 5, 3, 21]

If the list is sorted using the lst1.sort() the result is still not correct:

Blockquote
lst1 = [1, 2, 10, 4, 20, 5, 3, 21, 40]
lst1.sort()
for num in lst1:
if (num % 2) == 0:
lst1.remove(num)

print(lst1)
output: [1, 3, 5, 20, 21]

The only way to get the expected result is to use the sorted() python function

Blockquote
lst1 = [1, 2, 10, 4, 20, 5, 3, 21, 40]
for num in sorted(lst1):
if (num % 2) == 0:
lst1.remove(num)

print(lst1)
output: [1, 5, 3, 21]

I tried the above code using Python 3.8.5 and 3.9.2 but the results are always the same. As far as I know, a list of integers should not be sorted before working with it. So what is the problem?

The remove() method modifies the list in-place while the for-loop iterates over the elements. This is error prone:

lst1 = [1, 2, 10, 4, 20, 5, 3, 21, 40]
for n in lst1:
    print(n)
    if (n % 2) == 0:
        lst1.remove(n)

Output:
1
2
4
5
3
21
40

You can find that some elements appear “skipped” by the iteration, and they remain in the list afterwards.

Instead of in-place modification, you can build a new list as you iterate over the input one:

new_list = [n for n in lst1 if (n % 2) != 0]

or

def is_odd(n):
    return (n % 2) != 0
new_list = list(filter(is_odd, lst1))
1 Like

So what is the problem?

You are mutating the list at the same time as you are iterating over it. (Print
out the value used at each iteration to see what happens.)

You could do this instead:

for n in lst[:]:
    # code

to iterate over a copy of the list.

You could also make a new list via a comprehension, as so:

lst2 = [x for x in lst if x % 2]

Generally speaking, list.remove() is a bit expensive to do it in a loop, read
more about it here:

https://wiki.python.org/moin/TimeComplexity

1 Like

Great feedback Cong.

Thank you

1 Like

Thank you Marco.
Great inside. I really appreciate it