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
?
Using index() method First, iterate through the sublist in the nested list, then check if that particular element exists in that sub_list . If it exists, find the index of the sub_list and the index of the element in that sub_list .
We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.
Find an element using the list index() method. To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.
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
Here's a recursive version that works for any level of nesting.
def in_nested_list(my_list, item):
"""
Determines if an item is in my_list, even if nested in a lower-level list.
"""
if item in my_list:
return True
else:
return any(in_nested_list(sublist, item) for sublist in my_list if isinstance(sublist, list))
Here are a few tests:
x = [1, 3, [1, 2, 3], [2, 3, 4], [3, 4, [], [2, 3, 'a']]]
print in_nested_list(x, 2)
print in_nested_list(x, 5)
print in_nested_list(x, 'a')
print in_nested_list(x, 'b')
print in_nested_list(x, [])
print in_nested_list(x, [1, 2])
print in_nested_list(x, [1, 2, 3])
True
False
True
False
True
False
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With