Kutoff
Kutoff

Reputation: 384

Python slice notation to take only the start and the end part of a list?

Is there a way to use the slice notation to take only the start and end of a list?

eg 10 items from the start and 10 items from the end?

Upvotes: 2

Views: 313

Answers (2)

John La Rooy
John La Rooy

Reputation: 304473

You can replace the items in the middle with an empty list

>>> a = list(range(100))
>>> a[10:-10] = []
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

Doing it this way doesn't give an overlap, just the entire list if there isn't enough items

>>> a = list(range(15))
>>> a[10:-10] = []
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Even works in a sane way for @abarnert's case

>>> a = list(range(3))
>>> a[10:-10] = []
>>> a
[0, 1, 2]

Upvotes: 3

abarnert
abarnert

Reputation: 366133

Not directly… but it's very easy to use slicing and concatenation together to do it:

>>> a = list(range(100))
>>> a[:10] + a[-10:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

Of course if there are fewer than 20 items in the list, you will get some overlapped values:

>>> a = list(range(15))
>>> a[:10] + a[-10:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

… but you're getting literally what you asked for: 10 items from the start, and 10 items from the end. If you want something different, it's doable, but you need to define exactly what you want.

Upvotes: 4

Related Questions