+ 1

Searching in lists in a list python3

Hey, I have lists in a list for example: List = [[“a,”b”],[“fed,”Fr”]] and I like to check whether “fed” is in any of those list. Furthermore i’d like to do this in one line. My solution so far: if True in ([“fed” in i for i in List]) Any better solutions?

20th Aug 2019, 3:14 PM
clemens
6 Answers
+ 3
I would do this: if any('fed' in sublist for sublist in List): ...
20th Aug 2019, 5:08 PM
HonFu
HonFu - avatar
+ 4
clemens, 'return' can only be used from within functions.
20th Aug 2019, 4:53 PM
Lothar
Lothar - avatar
+ 3
[Updated] You. an also use 2 for loops for that: lst = [["a","b"],["fed","Fr"]] for i in lst: for j in i: if "fed" in j: res = True if "fed" in j else False print(res)
20th Aug 2019, 3:36 PM
Lothar
Lothar - avatar
+ 3
Code is updated to show True or False.
20th Aug 2019, 3:57 PM
Lothar
Lothar - avatar
+ 2
Thanks for the answer. is there anyway, that i just get a True or False as a reasult?
20th Aug 2019, 3:43 PM
clemens
+ 2
why does something like this dont work? [return True if 'fed' in x for i,x in enumerate([['a','b'], [ 'fed','fr']])]
20th Aug 2019, 4:04 PM
clemens