0

I have a nested list of Python strings, like this one:

l = [['a', 'b', 'c'], ['d', 'e', 'f']]

I would like to quickly test if a given string is equal to any of the strings in any of the sublists. I could write a function to flatten the list, but the test needs to happen in a time-critical portion of my program. Is there a faster or more elegant way to do this?

Matthew
  • 306
  • 4
  • 17

1 Answers1

7

You can't avoid having to loop and scan through elements here; but you can at least avoid having to scan all lists, and delegate the task of scanning each sublist to Python C code.

Use the any() function to test each sublist in a generator expression:

any(search in sublist for sublist in l)

any() will stop iterating over the generator expression the moment if finds a True value (e.g. when search in sublist found a match).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • This is the best solution because it short-circuits. It will at worst be O(N), but it must be by definition of the problem. At best you will hit the short circuit and bail earlier. – Cory Kramer Jan 14 '15 at 21:05