Skip to content
Advertisement

How do you extract till the second last element from each sub-list in a nested list?

How do you extract till the second last element from each sub-list in a nested list?

x = [[1, 2, 3], [4, 5], [7, 8, 9], [1, 3, 5, 6, 8]]

The desired output is:

y = [[1, 2], [4], [7, 8], [1, 3, 5, 6]]

Advertisement

Answer

You can use the following method to do this:

x = [[1, 2, 3], [4, 5], [7, 8, 9], [1, 3, 5, 6, 8]]
y = [sublist[:-1] for sublist in x]

output:

[[1, 2], [4], [7, 8], [1, 3, 5, 6]]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement