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

The slicing examples in the documentation show only whole literals and variables used as indexes, and not more complex expressions (for example, myarray[x/3+2:x/2+3:2] ). PEP-8 also does not cover this case. What is the usual use of spaces 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 seems to be no other reasonable options)?

+6
source share
2 answers

I have never seen spaces used in truncated operations, therefore I would be mistaken aside, avoiding them. Again, if this is not critical, I would be inclined to move the expressions outside the cutting operation at all. In the end, your goal is readability:

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

I believe the most relevant PEP8 conclusion on this issue is:

The recommendations given here are designed to improve readability of the code and make it consistent across a wide range of Python code.

In this case, my personal choice is likely to be either Steve Maine's answer, or perhaps:

 myarray[slice(x / 3 + 2, x / 2 + 3, 2)] 
+3
source

All Articles