-2

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.

1
  • 1
    This is an example of why you should not modify a collection whilst iterating over it. You should really be creating a new list with some elements from the old list. Commented Jul 30, 2022 at 9:52

2 Answers 2

3

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] 
Sign up to request clarification or add additional context in comments.

Comments

2

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%20reason%20to%20why%20you,list%20of%20just%20odd%20numbers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.