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!
Answers:
Try this:
lst = [item for item in lst if item[1] is not None]
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.
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))
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!
Try this:
lst = [item for item in lst if item[1] is not None]
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.
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))