Reputation: 29
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]]
Upvotes: 1
Views: 338
Reputation: 640
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]]
Upvotes: 4