Search code examples
pythonslicenotation

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?


Solution

  • 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.