Home > Mobile >  Delete a list from collection of lists
Delete a list from collection of lists

Time:03-11

I have collection of lists like this:

example = [['a','b','c'],['d','e','f'],[ ],[z],['g','h','i'],[ ],[z]]

I want to remove [] and [z] from the list. The desired output is:

example = [['a','b','c'],['d','e','f'],['g','h','i']]

How can I do it? Can I remove both using an one liner? I am familiar with .pop() and .remove() command but I have doubts if it will work for [ ] type of list.

CodePudding user response:

You can use list comprehension for the filtering:

example = [['a','b','c'],['d','e','f'],[ ],['z'],['g','h','i'],[ ],['z']]

output = [sublst for sublst in example if sublst not in ([], ['z'])]
print(output) # [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

CodePudding user response:

Some possibilities:

example = [['a','b','c'],['d','e','f'],[ ],['z'],['g','h','i'],[ ],['z']]

example.remove([])
example.remove([])
example.remove(['z'])
example.remove(['z'])

or

del example[2]
del example[3]
del example[5]
del example[-1]

or

example = [i for i in example if i != [] and i != ['z']]

or

for i in range(len(example)-1, 0,-1):
    if example[i] in  ([],['z']):
         del example[i]

CodePudding user response:

you can remove them like this:

example = list(filter(lambda val: val !=  [] and val!=['z'], example))
  • Related