The Python Oracle

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

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

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Question
00:42 Accepted answer (Score 6)
00:59 Answer 2 (Score 4)
01:27 Answer 3 (Score 1)
01:43 Answer 4 (Score 1)
02:17 Thank you

--

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

Answer 2 links:
[flatten]: https://stackoverflow.com/a/952952/52767...

--

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