2

Given a list of lists A with at most one layer of nesting, and an element to search for…

A = [1,2,3,[4,5,6,7],8,9,10]
to_find = 5

What is the fastest way to check whether an element with value 5 exists in A or not? List won't be sorted, and the index of element is of no concern.

I can iterate through A and check if element is a list and then check in there recursively.

Is there any better and faster way to do it?

200_success
  • 7,286
  • 1
  • 43
  • 74
user3089927
  • 3,575
  • 8
  • 25
  • 33
  • How many levels of nesting can be in `A`? – myaut Nov 10 '15 at 22:42
  • What kind of result are you looking for? – Javier Conde Nov 10 '15 at 22:44
  • Single level : A = [1,2,3,[4,5,6,7],8,9,10,[11,12,13]]. It will never be A = [1,2,3,[4,5,[6,7,8]]]. But I would like to know that use case too. – user3089927 Nov 10 '15 at 22:44
  • @JavierConde if the value in to_find is present in A or not. – user3089927 Nov 10 '15 at 22:45
  • is the list always sorted? – R Nar Nov 10 '15 at 22:52
  • @letsc - This isn't a duplicate of that question. That question asks if it's possible to find the index of an entire sublist, while this one looks for an element within the `list` and within all sublists. – TigerhawkT3 Nov 10 '15 at 22:56
  • But 5 *doesn't* exist in A... also see [What is the fastest wa to flatten arbitrarily nested lists in Python](http://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python) and [Making flat list out of list-of-lists in Python](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – TessellatingHeckler Nov 10 '15 at 23:00
  • @TigerhawkT3 - SHouldve shared this answer. It gives the _coordinates_ of the element being searched – letsc Nov 10 '15 at 23:08

1 Answers1

0

Given the condition of "a list of lists" and "at most one level of nesting":

def search(A, to_find):
    return any(1 for x in A if (x == to_find or (isinstance(x, list) and to_find in x)))

(Edited in case you happen to look for a Falsy value like 0)

zehnpaard
  • 6,003
  • 2
  • 25
  • 40