Al_Iskander Al_Iskander - 23 days ago 10
Python Question

Check if an item is in a nested list

in a simple list following check is trivial:

x = [1, 2, 3]

2 in x -> True


but if it is a list of list, such as:

x = [[1, 2, 3], [2, 3, 4]]

2 in x -> False


how can this be addressed in order to return
True
?

Answer

Try this, using the built-in any function. It's the most idiomatic solution, and it's also efficient, because any short-circuits and stops as soon as it finds the first match:

x = [[1, 2, 3], [2, 3, 4]]
any(2 in sl for sl in x)
=> True
Comments