0

I need to take an array and remove every second element from the array. Always keep the first element and start removing with the next element. Example:

["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep"]

None of the arrays will be empty.

I figured that the element to be removed must have an odd index and tried to solve this problem using a for-loop and modulo:

def remove_every_other():
    for element in my_list:
        if my_list.index(element) % 2 != 0:
            my_list.remove(element)
    return my_list

When I run my code with the following lists:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list2 = ["hello", "goodbye", "hello again"]
my_list3 = [[1, 2], [1, 2]]
my_list4 = [["goodbye"], {"Great": "Job"}, ["Goodbye"]]

These are the results when I run my code and print the lists afterwards:

['hello', 'hello again']
[1, 3, 4, 6, 7, 9, 10]
[[1, 2], [1, 2]]
[['goodbye'], ['Goodbye']]

It seems odd to me that the code works for a list of strings (my_list2) as well as for a list of lists but (my_list4) but not if the list of lists contains integers instead of strings inside the inner lists (my_list3) or if it is a list containing integers instead of strings (my_list).

Does Python treat lists differently depending on their contents? I feel like that should not matter here since I am checking the indexes of the elements and not the values itself.

I'm using Python 3.

Ben the Coder
  • 539
  • 2
  • 5
  • 21
Hades
  • 11
  • 2
  • 3
    Try doing `my_list[::2]` – It_is_Chris Feb 23 '23 at 15:22
  • [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – buran Feb 23 '23 at 15:23
  • Does [that answer](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) help you? – Florent Monin Feb 23 '23 at 15:23
  • 1
    Btw, it "seems" to work for the list of string, but it's a special case because the list has just 3 elements. i.e. not because of type, but because the length of the original list is 3 – buran Feb 23 '23 at 15:27
  • Okay I mostly got where I was thinking wrong, thanks a lot! Why doesn't the code work for a list with 2 elements though? In this case the modifying of the list shouldn't mess with the indices right? – Hades Feb 23 '23 at 15:39

2 Answers2

0

Consider the side effects of mutating the list you are iterating over.

For the example of my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

When you reach your first odd index, you are altering the exact list you continue to iterate over. Your new list looks like this:

[1, 3, 4, 5, 6, 7, 8, 9, 10]

You've changed the size! This means all the indexes are different, and the for loop continues onto the following index. This is hard to reason about.

Often, it's conceptually simpler and less error-prone to build a new list with the values you want. Maybe something like:

def remove_every_other(my_list):
    new_list = []
    # enumerate is a pythonic alternative for doing your my_list.index(element) idea
    for idx, element in enumerate(my_list):
        if idx % 2 == 0:
            new_list.append(element)
    return new_list

fraczles
  • 81
  • 3
0

You can solve this by removing that value whose index is an odd number.

def rem_odd_index_value(my_list):
    result = []
    for i in range(len(my_list)):
        if i%2==0:
            result.append(my_list[i])
    return result

print(rem_odd_index(my_list3))```