All elements aren't appearing when iterating through a loop

Viewed 46

My school assignment requires me to read a list from the user and then remove all odd elements from it. The loop I'm using to check for odd numbers doesn't even iterate through all the list elements.

ans=1
lst=[]
while ans!=0:
    no=int(input('Enter value for list or press 0 to exit:'))
    if no!=0:
        lst.append(no)
    else:
        break

print('\nYour list is:',lst)

       
for i in lst:     # loop to check for odd nos
    print('i is', i)
    if i%2==1:
        lst.remove(i)

print('List after removing odd elements:',lst)

In the second loop, I added the print statement to check the inconsistent output and here are the results: Output

Some of the list elements are skipped(?) when iterating and so they aren't removed which is giving me the incorrect output. Why could this be happening?

2 Answers

Creat a new list (to be allocated to lst) whitch select elements that respond to : elm%2 != 1

lst = [i for i in lst if i%2 != 1] #There will be no prints

With prints:

new_lst = []
for i in lst:
    print("i is ", i)
    if i%2 != 1:
       new_lst.append(i)
lst = new_lst

Can be also :

lst = list(filter(
    lambda x:( x % 2 ! = 1), #Each elements of lst is passed to this func
    lst                      #is the output of func is True (not 0) => add to list
))

First, you read only to numbers. Second, since we know for sure that we have a number, we do not need to add the number if it is not even. Read user inputs until they enter -1

    list_even = []
    while True:
        try:
            digit = int(input('Enter value digit: '))
            if digit == -1: break
            elif digit % 2 == 0:
                list_even.append(digit)
        except ValueError:
            print('error is not digit')
            pass
    print('evens: ', list_even)
Related