David Greydanus
David Greydanus

Reputation: 2567

How to search for an item in a list of lists?

How can I do something like this.

index=[[test1,test2,test3],[test4,test5,test6],[test7,test8,test9]]
if test5 is in index:
    print True

Upvotes: 1

Views: 146

Answers (5)

Smita K
Smita K

Reputation: 94

try by this way

index = [['test1','test2','test3'], ['test4','test5','test6'], ['test7','test8','test9']]
any(filter(lambda x : 'test5' in x, index))

Upvotes: 2

Himanshu
Himanshu

Reputation: 2454

Or perhaps try itertools to unroll the array :-

index=[[test1,test2,test3],[test4,test5,test6],[test7,test8,test9]]
if test5 in itertools.chain(*index):
    print True

Upvotes: 1

Michael_Scharf
Michael_Scharf

Reputation: 34508

try

index=[[test1,test2,test3],[test4,test5,test6],[test7,test8,test9]]
flat_index=[item for sublist in index for item in sublist]
if test5 is in flat_index:
    print True

see also Making a flat list out of list of lists in Python

Upvotes: 0

Ayush
Ayush

Reputation: 42450

Loop over your list of lists, and check for existence in each inner list:

for list in list_of_lists:
  if needle in list :
    print 'Found'

Upvotes: 2

falsetru
falsetru

Reputation: 369074

Using any + generator expression:

if any(test5 in subindex for subindex in index):
    print True

Upvotes: 8

Related Questions