Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove even numbers from a list in Python? [duplicate]

I'm trying to remove even numbers from a list. My final output is [4,8] but it is supposed to be empty.

list = [2, 4, 6, 8, 10]
for i in list:
    divid = i %2
    if divid == 0 :
        list.remove(i)
print(list)
like image 293
Ehsan Omar Avatar asked Mar 07 '26 17:03

Ehsan Omar


2 Answers

You are modifying the list as you iterate over it. Imagine a pointer moving along the list. For the first iteration, the index is 0 (and i is 2). You remove the first value and return to the start of the loop.

The index is incremented (to 1) and i is now the second value in the list (now 6) which is also removed. Notice that 4 is now 'behind' the index of the iterator and will never be reached. Continuing along the list you will remove every second value leaving [4, 8].

A couple of pointers. To loop over a list like this you can use for i in list[:]: which copies the list before iterating over it. Also avoid naming variables things like list which override builtin types. You'll cause bugs later in your code.

like image 106
Holloway Avatar answered Mar 09 '26 07:03

Holloway


As others have pointed out, you should not modify a list and iterate over it at the same time. The simplest solution is to create a new list with the required modifications:

lst = [2, 4, 6, 8, 10]
new_lst = [i for i in lst if i % 2 != 0]

The above uses a list comprehension to create a new list with only the odd elements - which is the same as removing the even elements from the original list.

like image 44
Óscar López Avatar answered Mar 09 '26 06:03

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!