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
.