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]]
>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)