Home > Blockchain >  Remove a tuple in a tuple of tuples based on condition
Remove a tuple in a tuple of tuples based on condition

Time:11-05

I have the following tuple of tuples:

lst = (('a',102, True), ('b', None, False), ('c', 100, False))

I'd like to remove any tuples 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!

CodePudding user response:

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.

CodePudding user response:

Try this:

lst = [item for item in lst if item[1] is not None]

CodePudding user response:

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

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

# (('a', 102, True), ('c', 100, False))

Or for any position:

lst = tuple(filter(lambda i: None not in i, lst))

# (('a', 102, True), ('c', 100, False))
  • Related