-1

I have to make a code for class where I am given a list and I have to tell how many even numbers there are. I made this code and it is able to give me a correct answer

list = [3,5,6,4,8,12,55,78]

def countEvenList(list):
    evens = 0
    for i in range(len(list)):
        if(list[i]%2==0):
            evens = evens + 1
        else:
            evens = evens + 0
            pass
    print(evens)
    print(list)

countEvenList(list)

But the second part of the assignment I am not being able to complete. I have to make it that it removes/deletes the number that its checking.

For example on the list

list = [3,5,6,4,8,12,55,78]

Each time it check each number it has to be removed of the list

I tried doing this.

list = [3,5,6,4,8,12,55,78]

def countEvenList(list):
    evens = 0
    for i in range(len(list)):
        if(list[i]%2==0):
            evens = evens + 1
            list.pop(0)
        else:
            evens = evens + 0
            list.pop(0)
            pass
    print(evens)
    print(list)

countEvenList(list)

But it gives me the error "IndexError: list index out of range".

Why is that? and what should I do so that it works?

P.S. I know things like list.clear exist, but I was told not to use is since the purpose is to make it that each number that it checks it's removed.

1 Answers1

0

It is not possible to loop and delete list elements from the forward simultaneously, consider using a while loop or reverse for loop, but the readability will be a little worse, refer to the following code.

def countEvenList1(lst):
    events = 0
    for item in range(len(lst) - 1, -1, -1):
        if lst[item] % 2 == 0:
            events += 1
        del lst[item]
    print(events, lst)


def countEvenList2(lst):
    events = 0
    while len(lst):
        if lst[0] % 2 == 0:
            events += 1
        del lst[0]
    print(events, lst)


countEvenList1([3,5,6,4,8,12,55,78])
countEvenList2([3,5,6,4,8,12,55,78])

You can also try copying a new list to achieve this. Also, it is not recommended that you use python keywords as variable names, such as "list" in your example

maya
  • 1,029
  • 1
  • 2
  • 7