19

I have a list like following

mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]

how do I see if the list contains 'value2'?

Tommyka
  • 665
  • 1
  • 5
  • 9
  • If you want to see the index of the value within the 2 dimensional list, I used this answer: https://stackoverflow.com/a/6518412/1799272 – Oli4 Feb 04 '18 at 14:21

4 Answers4

39

Use any():

any('value2' in sublist for sublist in mylist)
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Thanks, I am curious if there is a way to get the item that was matched? – Tommyka Oct 09 '12 at 21:37
  • 2
    To get the item that contains the value you are looking for, you should use a regular `for` loop and return or break when `'value2'` exists in the list. If you want to find all matching items, you can use `[sublist for sublist in mylist if 'value2' in sublist]`. – Andrew Clark Oct 09 '12 at 21:42
11

You can simply check all sublists with any:

any('value2' in subl for subl in mylist)
phihag
  • 278,196
  • 72
  • 453
  • 469
4
'value2' in (item for sublist in mylist for item in sublist)
ErwinP
  • 402
  • 3
  • 9
0

similar to any(), a solution that also supports short-circuiting :

>>> from itertools import chain
>>> mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]
>>> 'value2' in chain(*mylist)
True

proof that it short-circuits like any():

>>> it=chain(*mylist)
>>> 'value2' in it
True
>>> list(it) #part of iterable still not traversed
['value3', 'secval1', 'secval2', 'secval3']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • `any` already does short-circuiting. Test it by creating a class that defines `__nonzero__`, put a `print` statement in there, and use it as the second value in the argument to `any` (when the first is `True`). The `print` statement will not get executed. – Benjamin Hodgson Oct 09 '12 at 19:43
  • @poorsod I know that, that's why I said `"similar to any()"`. :) – Ashwini Chaudhary Oct 09 '12 at 19:44
  • Oh, I misunderstood - thought you were suggesting a replacement for `any` that uses short-circuiting. – Benjamin Hodgson Oct 09 '12 at 19:45