Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an item is in a nested list

Tags:

python

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?

like image 758
Al_Iskander Avatar asked Nov 09 '16 19:11

Al_Iskander


People also ask

How do you check if a value exists in a nested list?

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 .

How do you check if an element is in a 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.

How do you find the list of elements in a 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.


2 Answers

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
like image 145
Óscar López Avatar answered Sep 30 '22 07:09

Óscar López


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
like image 34
Curt F. Avatar answered Sep 30 '22 06:09

Curt F.