Skip to content Skip to sidebar Skip to footer

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 o

Solution 1:

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

out = [[l[-1] for l in v] for v in lst]
print(out)

Prints:

[[15, 14, 15, 17, 17], [18, 17]]

Solution 2:

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)

Post a Comment for "How To Extract The Last Item From A List In A List Of Lists? (python)"