Keep only first and last element of sublists in python

Question:

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]]
Asked By: chippycentra

||

Answers:

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)

Answered By: Stef

You can use the following:

inp = [[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15]]
outp = [[x[0], x[-1]] for x in inp]

This makes the last element [15, 15] though – if that is not acceptable, you can use this:

outp = [[x[0], x[-1]] if len(x) > 1 else [x[0]] for x in inp ]
Answered By: rep_movsd

Another variation using destructuring with a pinch of asterisk:

[[a, b[-1]] if b else [a] for a, *b in my_list]
Answered By: fsimonjetz

This is clumsy way.
Just look for fun.

da_list = [[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14],[15]]
result = []
for i in da_list :
    try :
        i.pop(1)
    except: continue    
    result.append(i)
print (result)
Answered By: Lorewalker Cho
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.