Home > database >  Keep only first and last element of sublists in python
Keep only first and last element of sublists in python

Time:08-24

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

CodePudding user response:

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)

CodePudding user response:

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 ]

CodePudding user response:

Another variation using destructuring with a pinch of asterisk:

[[a, b[-1]] if b else [a] for a, *b in my_list]

CodePudding user response:

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)
  • Related