Tommyka
Tommyka

Reputation: 675

How to determined if a 2 dimensional list contain a value?

I have a list like following

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

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

Upvotes: 20

Views: 41840

Answers (4)

ErwinP
ErwinP

Reputation: 412

'value2' in (item for sublist in mylist for item in sublist)

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

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']

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208665

Use any():

any('value2' in sublist for sublist in mylist)

Upvotes: 40

phihag
phihag

Reputation: 288260

You can simply check all sublists with any:

any('value2' in subl for subl in mylist)

Upvotes: 12

Related Questions