Reputation: 7225
The first and last N elements of a list in Python can be gotten using:
N = 2
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[:N] + my_list[-N:])
# [0, 1, 4, 5]
Is it possible to do this with a single slice in pure Python? I tried my_list[-N:N]
, which is empty, and my_list[N:-N]
, which gives exactly the elements I don't want.
Upvotes: 0
Views: 92
Reputation: 50076
For the builtin types, slices are by definition consecutive – a slice represents a start, end and step between them. There is no way for a single slice operation to represent non-consecutive elements, such as head and tail of a list.
Upvotes: 1