Home > Net >  How to find the sublist containing a specific element in python3 without defining a function?
How to find the sublist containing a specific element in python3 without defining a function?

Time:03-28

In a list of sublists,

lst = [[2,4,5,6], [0,1,3,7], [], ... , [8,9], [10, 11,12]]

find the sublist that has a specific element, say 9:

(Knowing that all elements are unique)

output: [8, 9] 

CodePudding user response:

You can ask for the next sublist in the list if 9 is in the sublist with None if it is not found:

lst = [[2,4,5,6], [0,1,3,7], [],  [8,9], [10, 11,12]]

next((l for l in lst if 9 in l), None)
# [8, 9]
  • Related