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

Keep only first and last element of sublists in python

I have a list such as : [[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15]]

How can I select within each sublist only the first and last element, such as :

expected_list=[[0,2],[3,5],[6,8],[9,11],[12,14],[15]]

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

>Solution :

use list comprehension:

l = [[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15]]


expected_list = [[x[0], x[-1]] if len(x) > 1 else [x[0]] for x in l]

To be on the safe side, you could also check for empty lists:

[[x[0], x[-1]] if len(x) > 1 else [x[0]] if len(x) else [] for x in l]

Alternative:

[x[0::len(x)-1] if len(x) > 1 else x.copy() for x in l]

(x.copy() thanks to @mozway see comment)

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