I have a list of lists. I am trying to remove elements 0,1 and 4 from each of the sub-lists using a for loop. Is this possible? When I try to use the del function it removes the first and second list instead.
my_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i' ,'j', 'k'], ['l', 'm', 'n', 'o']]
for sublist in my_list:
del my_list[0:1:4]
print(my_list)
#Output
>>>[['l', 'm', 'n', 'o']]
#Intended output
>>>[['c', 'd'], ['h','i','k'], ['n',]]
you can loop over the inner lists with enumerate which will return the indexes and the values and append to a new list if the index is not 0, 1, or 4:
outputs:
(I believe there is an error in your example as 'o' is at index 3, as indexes start at 0 in python)
Alternatively, you can remove the items in place by looping over the indices to remove in reverse order: