Search code examples
pythoncoding-stylewhitespace

What is the recommended whitespace for slicing with expression indices in Python?


Examples of slicing in documentation only show integer literals and variables used as indices, not more complex expressions (e.g. myarray[x/3+2:x/2+3:2]). PEP-8 also doesn't cover this case. What is the usual usage of whitespace here: myarray[x/3+2:x/2+3:2], myarray[x/3+2 : x/2+3 : 2], or myarray[x/3+2: x/2+3: 2] (there don't seem to be other reasonable options)?


Solution

  • I have never seen spaces used in slicing operations, so would err on the side of avoiding them. Then again, unless it's performance critical I'd be inclined to move the expressions outside of the slicing operation altogether. After all, your goal is readability:

    lower = x / 3 + 2
    upper = x / 2 + 3
    myarray[lower:upper:2]