Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

output: [8, 9] 

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading