The Python Oracle

How do I search a list that is in a nested list (list of list) without loop in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 How Do I Search A List That Is In A Nested List (List Of List) Without Loop In Python?
00:33 Answer 1 Score 1
00:59 Answer 2 Score 1
01:12 Accepted Answer Score 6
01:26 Answer 4 Score 4
01:47 Thank you

--

Full question
https://stackoverflow.com/questions/3539...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 6


you can use chain from itertools to merge the lists and then search in the returned list.

>>> sample=[[1,[1,0]],[1,1]]
>>> from itertools import chain
>>> print [1,0]  in chain(*sample)
True



ANSWER 2

Score 4


A recursive solution that would work for arbitrary (max recursion depth aside) deep nesting. Also works if any elements of the outermost list are not iterables themselves.

from functools import partial

def contains_nested(some_iterable, elmnt):
    try:
        if elmnt in some_iterable:
            return True
    except TypeError:  # some_iterable is not iterable
        return False
    else:
        return any(map(partial(contains_nested, elmnt=elmnt), some_iterable))



ANSWER 3

Score 1


I don't know how to solve this completely without a loop. But in Python you should never write for i in range(len(sample)).

So the answer to your question: Yes there is a better and faster way you could loop your list for i in sample

The way Python handles the loops is really fast and works also very well with a lot of entriey (more than 50.000).




ANSWER 4

Score 1


You can flatten your sample list and then search in that flattened list:

> sample = [[1, [1, 0]], [1, 1]]
> [1, 0] in [item for sublist in sample for item in sublist]
> True