1

How can I do something like this.

index=[[test1,test2,test3],[test4,test5,test6],[test7,test8,test9]]
if test5 is in index:
    print True
Ayush
  • 3,989
  • 1
  • 26
  • 34
David Greydanus
  • 2,551
  • 1
  • 23
  • 42

5 Answers5

8

Using any + generator expression:

if any(test5 in subindex for subindex in index):
    print True
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

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'
Ayush
  • 41,754
  • 51
  • 164
  • 239
2

try by this way

index = [['test1','test2','test3'], ['test4','test5','test6'], ['test7','test8','test9']]
any(filter(lambda x : 'test5' in x, index))
Smita K
  • 94
  • 5
1

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
Himanshu
  • 2,384
  • 2
  • 24
  • 42
0

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

Community
  • 1
  • 1
Michael_Scharf
  • 33,154
  • 22
  • 74
  • 95