1

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',
]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
KDrago
  • 33
  • 4
  • 3
    It's what I would consider an unidiomatic way of doing `sys.path.insert(0, )` Or rather, `for something in : sys.path.insert(0, something)` – juanpa.arrivillaga Mar 06 '17 at 21:51
  • But basically, assignment to a list slice modifies the list in-place. This slice: `my_list[0:0]` is actually nothing, but if you assign to it, it inserts to the left-most place. If you assign to a slice too "far to the right" it essentially adds to the right-most part. – juanpa.arrivillaga Mar 06 '17 at 21:52
  • This is [Slice Assignment](http://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice) – Wondercricket Mar 06 '17 at 22:06
  • Okay, great! Thank you for the responses. – KDrago Mar 07 '17 at 15:08

1 Answers1

6

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]
DevLounge
  • 8,313
  • 3
  • 31
  • 44