Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index the first and the last n elements of a list

Tags:

python

list

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?

like image 410
user1934212 Avatar asked Oct 13 '16 08:10

user1934212


1 Answers

Just concatenate the results:

l[:3] + l[-3:]

There is no dedicated syntax to combine disjoint slices.

like image 141
Martijn Pieters Avatar answered Oct 19 '22 11:10

Martijn Pieters