Reputation: 9213
What is wrong with my search within a list of list? The output should be It's there
mylist = [['a','b','c'],['d','e','f']]
if 'a' in mylist:
print "It's there"
else:
print "it's not there"
Upvotes: 0
Views: 76
Reputation: 16711
Chain the nested lists and do as you normally would:
'a' in itertools.chain.from_iterable(mylist)
Alternatively, you can check each item in the list:
any('a' in item for item in mylist)
Upvotes: 3
Reputation: 113975
'a'
is not in mylist
; rather, it is in one of the lists contained within mylist
:
In [240]: for sublist in mylist:
.....: if 'a' in sublist:
.....: print("'a' exists in", sublist)
.....:
'a' exists in ['a', 'b', 'c']
So, if you'd like to check if an element exists in any of many sub-lists:
In [241]: any('a' in sublist for sublist in mylist)
Out[241]: True
Upvotes: 2
Reputation: 2398
'a' is not in your list of course. Your list has two elements, each of which is a list. To look for 'a' within every list contained in your list, you need to flatten the lists into one list and search within that.
Upvotes: 0