pythonlistfor-loopsublist

How do I use a for loop to remove elements from each sublist in a list of list


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',]]

Solution

  • 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:

    my_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i' ,'j', 'k'], ['l', 'm', 'n', 'o']]
    
    new_list = []
    
    for l in my_list:
        new_list.append([n for i, n in enumerate(l) if i not in {0, 1, 4}])
    
    print(new_list)
    

    outputs:

    [['c', 'd'], ['h', 'i', 'k'], ['n', 'o']]
    

    (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:

    my_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i' ,'j', 'k'], ['l', 'm', 'n', 'o']]
    
    for l in my_list:
        for i in [4, 1, 0]:
            if i < len(l):
                del l[i]
    
    print(my_list)  # [['c', 'd'], ['h', 'i', 'k'], ['n', 'o']]