List of lists: how to delete all lists that contain certain values?
Question:
There’s a list of lists (or it could be tuple of tuples). For example:
my_list = [
['A', 7462],
['B', 8361],
['C', 3713],
]
What would be the most efficient way to filter out all lists that have a value 'B'
in them, considering that the number (or other values) might change?
The only way I came up with so far is using a for/in cycle (or rather a list comprehension) but it’s very inefficient in this case, so I’d like to know if it’s possible to avoid using a loop.
Answers:
You can create a new list, filtering out the stuff you don’t want. In python this is usually done with a list comprehension:
new_list = [sublist for sublist in my_list if sublist[0] != 'B']
There’s a list of lists (or it could be tuple of tuples). For example:
my_list = [
['A', 7462],
['B', 8361],
['C', 3713],
]
What would be the most efficient way to filter out all lists that have a value 'B'
in them, considering that the number (or other values) might change?
The only way I came up with so far is using a for/in cycle (or rather a list comprehension) but it’s very inefficient in this case, so I’d like to know if it’s possible to avoid using a loop.
You can create a new list, filtering out the stuff you don’t want. In python this is usually done with a list comprehension:
new_list = [sublist for sublist in my_list if sublist[0] != 'B']