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.

Asked By: Lev Slinsen

||

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']
Answered By: tdelaney
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.