Remove a list in a list of lists based on condition

Question:

I have the following list of lists:

lst = [['a',102, True],['b',None, False], ['c',100, False]]

I’d like to remove any lists where the value in the second position is None. How can I do this (in a list comprehension)

I’ve tried a few different list comprehension but can’t seem to figure it out. Thanks!

Asked By: chicagobeast12

||

Answers:

Try this:

lst = [item for item in lst if item[1] is not None]
Answered By: user16004728

Use this:

lst = (('a',102, True),('b',None, False), ('c',100, False))
lst = tuple([el for el in lst if el[1] is not None])
print(lst)  # => (('a', 102, True), ('c', 100, False))

Your data is a tuple of tuples, not a list of lists, so you need to convert it to a tuple at the end.

Answered By: Michael M.

Use filter and lambda to generate new tuple if lement in index 1 (second position) of inner tuple not equals None:

lst = tuple(filter(lambda i: i[1] != None, lst))

# (('a', 102, True), ('c', 100, False))
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.