Search code examples
pythonconventions

Explain the usage of 'some_list[0:0] = new_list'


I encountered this code that is giving a long list of file paths but I am curious what the significance of the [0:0] part of the code is but I can't seem to find any references to this specific syntax usage.

Would sys.path[0] = mean the same thing as sys.path[0:0]? Is that even a thing?

Since I can't seem to find reference to this kind of code, does that mean there is a better way to do this in newer versions of Python? I ask because I suspect the application using this code was build on Python 2.4.

import sys
sys.path[0:0] = [
  '/home/nac/eggs/Pillow-2.7.0-py2.7-linux-x86_64.egg',
...
...
...
 '/home/nac/eggs/pycparser-2.14-py2.7.egg',
]

Solution

  • It is equivalent to an update/insert:

    >>> numbers = [1, 2, 3]
    >>> numbers[0:0] = [4, 5, 6]
    >>> numbers
    [4, 5, 6, 1, 2, 3]
    

    Another example:

    numbers = [1, 2, 3]
    >>> numbers[0:2] = [4, 5, 6]
    >>> numbers
    [4, 5, 6, 3]