Reputation: 9635
the first n and the last n element of the python list
l=[1,2,3,4,5,6,7,8,9,10]
can be indexed by the expressions
print l[:3]
[1, 2, 3]
and
print l[-3:]
[8, 9, 10]
is there a way to combine both in a single expression, i.e index the first n and the last n elements using one indexing expression?
Upvotes: 8
Views: 6656
Reputation: 2888
If it is allowed to change list, You can use this:
del(a[n:-n])
If not, create new list and then do this.
b = [x for x in a]
del(b[n:-n])
Upvotes: 2
Reputation: 1121834
Just concatenate the results:
l[:3] + l[-3:]
There is no dedicated syntax to combine disjoint slices.
Upvotes: 8