How do you extract till the second last element from each sub-list in a nested list?
JavaScript
x
2
1
x = [[1, 2, 3], [4, 5], [7, 8, 9], [1, 3, 5, 6, 8]]
2
The desired output is:
JavaScript
1
2
1
y = [[1, 2], [4], [7, 8], [1, 3, 5, 6]]
2
Advertisement
Answer
You can use the following method to do this:
JavaScript
1
3
1
x = [[1, 2, 3], [4, 5], [7, 8, 9], [1, 3, 5, 6, 8]]
2
y = [sublist[:-1] for sublist in x]
3
output:
JavaScript
1
2
1
[[1, 2], [4], [7, 8], [1, 3, 5, 6]]
2