13

I am perfectly aware of that..

sample=[[1,[1,0]],[1,1]]
[1,[1,0]] in sample

This will return True.

But what I want to do here is this.

sample=[[1,[1,0]],[1,1]]
[1,0] in sample

I want the return to be True, but this returns False. I can do this:

sample=[[1,[1,0]],[1,1]]
for i in range(len(sample)):
    [1,0] in sample[i]

But I am wondering if there is any better or efficient way of doing it.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Kiwi Lee
  • 133
  • 4
  • You can use `for index, elem in enumerate(sample): [1, 0] in elem` over `range(len())` --unrelated, just cleaner – cat Feb 14 '16 at 16:14

4 Answers4

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
Alexander Oh
  • 24,223
  • 14
  • 73
  • 76
  • This would fail however if any element of the initial list is not iterable. – user2390182 Feb 14 '16 at 10:43
  • 2
    the question says list of lists. if you want to find lists in an arbitrary structure this would be entering parsing territory. where pattern matching or visitors would perhaps apply. (note that both would require traversal of a set of known structures). – Alexander Oh Feb 14 '16 at 12:39
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))
user2390182
  • 72,016
  • 6
  • 67
  • 89
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).

apxp
  • 5,240
  • 4
  • 23
  • 43
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
Community
  • 1
  • 1
bastelflp
  • 9,362
  • 7
  • 32
  • 67