rjk
rjk

Reputation: 29

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]]

Upvotes: 1

Views: 338

Answers (2)

xio
xio

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

Tim Jim
Tim Jim

Reputation: 670

You can try this:

y = [ar[:-1] for ar in x]

Upvotes: 0

Related Questions