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

57 Views Asked by At

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

There are 3 best solutions below

0
Tom McLean On BEST ANSWER

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']]
0
I'mahdi On

You can use List Comprehensions.

my_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i' ,'j', 'k'], ['l', 'm', 'n', 'o']]

del_list = {0, 1, 4}

res = [[l for idx, l in enumerate(lst) if idx not in del_list] for lst in my_list]

# You can re-write like the below
# res = [
#     [l for idx, l in enumerate(lst) if idx not in del_list] 
#     for lst in my_list
# ]

print(res)

[['c', 'd'], ['h', 'i', 'k'], ['n', 'o']]
0
Zero-nnkn On

Try this:

my_list = [sub[2:4] +sub[5:] for sub in my_list]
my_list
# [['c', 'd'], ['h', 'i', 'k'], ['n', 'o']]