2

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?

Ashley
  • 25
  • 3
  • 4
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – JeffUK Dec 03 '20 at 20:58
  • 1
    If you remove elements from the list while you're also iterating over that list, you will get interesting results. This question has some good answers that explain it a bit better https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it – JeffUK Dec 03 '20 at 20:59

2 Answers2

1

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
))
Henry
  • 577
  • 4
  • 9
0

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)