Home > Software engineering >  How do I create a remove every other element function?
How do I create a remove every other element function?

Time:07-30

I have written a script

def remove_every_other(my_list):
    # Your code here! 
    rem = False
    for i in my_list:
        if rem:
            my_list.remove(i)
        rem = not rem
    return my_list 

It removes every other element from the list.

I input [1,2,3,4,5,6,7,8,9,10] it returns [1,3,4,6,7,9,10]

Which to me is very strange also if I input [Yes,No,Yes,No,Yes] it outputs [Yes,No,Yes,No]

I have tried to figure it out for hours but couldn't get it to work, I am a beginner.

CodePudding user response:

You could just use slicing for that. Or do you want to do it explicitly in a loop? For an explanation of the syntax, you can follow the link. Basically you take the full list (no start or end defined) with a step-value of 2 (every other element). As others have pointed out, you run into problems if you're modifying a list that you're iterating over, thus the unexpected behavior.

input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
output_list = input_list[::2]
print(output_list)

This returns a copy of the list with every other element removed:

[1, 3, 5, 7, 9]

CodePudding user response:

Since .remove() is being called upon the same list that you're iterating over, the order is getting disarranged.

We could append the items that you want at the end in another list to maintain the ordering in the original list.

def remove_every_other(my_list):
    morphed_list = []
    
    rem = True
    for i in my_list:
        if rem:
            morphed_list.append(i)
        rem = not rem
        
    return morphed_list 

In general, it is not a good idea to modify the list you're iterating over. You could read more about it over here: https://stackoverflow.com/questions/10812272/modifying-a-list-while-iterating-over-it-why-not#:~:text=The reason to why you,list of just odd numbers.

  • Related