Search code examples
python-3.xlistsublist

How to extract the last item from a list in a list of lists? (Python)


I have a list of lists and would like to extract the last items and place them in a lists of lists. It is relatively easy to extract the last items. But all my attempts result in one list, rather than in a list of lists. Any suggestions?

lst = [[[11, 12, 15], [12, 13, 14], [13, 14, 15], [14, 15, 17], [15, 16, 17]], [[14, 15, 18], [15, 16, 17]]]

The result I would like from this is: [[15, 14, 15, 17, 17], [18, 17]]

What I tried for example, is this function:

def Extract(lst): 
    for i in lst:
        return [item[-1] for item in i]
print(Extract(lst))

But this only gives: [15, 14, 15, 17, 17]

I also tried:

last = []
for i in lst:
    for d in i:
        last.append(d[-1])
last

But this gives: [15, 14, 15, 17, 17, 18, 17]

Any suggestions how to get [[15, 14, 15, 17, 17], [17, 18]] as the outcome?


Solution

  • I would suggest looping through the list twice, like so:

    lst = [[[11, 12, 15], [12, 13, 14], [13, 14, 15], [14, 15, 17], [15, 16, 17]], [[14, 15, 18], [15, 16, 17]]]
    
    # Result of iteration
    last_lst = []
    
    # Iterate through lst
    for item1 in lst:
        # Initialize temporary list
        last_item1 = []
        
        #Iterate through each list in lst
        for item2 in item1:
            # Add last item to temporary list
            last_item1.append(item2[-1])
            
        # Add the temporary list to last_lst
        last_lst.append(last_item1)