Oblomov
Oblomov

Reputation: 9635

Index the first and the last n elements of a 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?

Upvotes: 8

Views: 6656

Answers (4)

Fejs
Fejs

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

Gildas
Gildas

Reputation: 1128

Do you mean like:

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

then using variable:

l[:x]+l[-y:]

Upvotes: 3

S. de Melo
S. de Melo

Reputation: 856

No, but you can use:

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

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Just concatenate the results:

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

There is no dedicated syntax to combine disjoint slices.

Upvotes: 8

Related Questions