I would like to move elements from one list to another based on a separate boolean list. I attempted the following pattern but pop at an early index shortens the list and I run into an IndexError at later elements.
list_1 = [1, 2, 3, 4]
list_2 = []
to_move = [True, False, False, True]
for idx, element in enumerate(to_move):
if element:
list_2.append(list_1.pop[idx]) #at element 4 (index 3), list_1 has already had its indices changed and cannot pop based on index 3
Another way might be to remove elements AFTER initial move, but I currently run into the same problem.
list_1 = [1, 2, 3, 4]
list_2 = []
to_move = [True, False, False, True]
for idx, element in enumerate(to_move):
if element:
list_2.append(list_1[idx])
for idx, element in enumerate(to_move):
if element:
list_1.remove(idx) # is there a way to remove all elements at once based on index?
If there is a way to move/remove all elements in a list at once (ie. without losing index spot in list), thus avoiding an IndexError?