0

This function will repeatedly remove the first element of a list until it finds an odd number or runs out of elements. It will accept a list of numbers as an input parameter and return the modified list where any even numbers at the beginning of the list are removed. To do this, we will need the following steps:

  1. Define our function to accept a single input parameter my_list which is a list of numbers

  2. Loop through every number in the list if there are still numbers in the list and if we haven’t hit an odd number yet

  3. Within the loop, if the first number in the list is even, then remove the first number of the list

  4. Once we hit an odd number or we run out of numbers, return the modified list

I wrote a function called delete_starting_evens() that has a parameter named my_list.

The function should remove elements from the front of my_list until the front of the list is not even. The function should then return my_list.

For example, if my_list started as [4, 8, 10, 11, 12, 15], then delete_starting_evens(my_list) should return [11, 12, 15].

My code:

def delete_starting_evens(my_list):
    for i in my_list:
        if i % 2 == 0:
            my_list.remove(i)
        else:
            break
    return my_list
a=[4,8,10,12,14,15,16,17,19,20]
print(delete_starting_evens(a))

The problem is that the function was removing the even indexes. I was expecting that the function should delete the even numbers until it finds the odd number or runs out of elements. How to solve it?

  • Don't remove elements from a list as you iterate over it. – Pranav Hosangadi Jul 27 '23 at 13:29
  • @PranavHosangadi I agree, he should probably make a second list maybe – LiterallyGutsFromBerserk Jul 27 '23 at 13:32
  • 1
    Just to show the power of Python, a solution with `itertools` from the standard library. You need only one line of code: `a[:] = list(itertools.dropwhile((lambda x: x % 2 == 0), a))`. If it is not necessary to change the original list - as the question suggests - `a = ...` is sufficient. – Matthias Jul 27 '23 at 14:03

1 Answers1

-1
def delete_starting_evens(my_list):
    idx=-1
    for i in my_list:
        if i % 2 == 1:
            idx = my_list.index(i)
            break
    if(idx==-1):
       return []
    else:
        second_list = my_list[idx:]
        return second_list
a=[4,5,8,10,12]
print(delete_starting_evens(a))