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)?
Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .
Second note, when no start is defined as in A[:2] , it defaults to 0. There are two ends to the list: the beginning where index=0 (the first element) and the end where index=highest value (the last element).
Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.
The slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.
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]
I believe the most relevant extract of PEP8 on this subject is:
The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code.
In this case, my personal choice would probably be either Steve Mayne's answer, or perhaps:
myarray[slice(x / 3 + 2, x / 2 + 3, 2)]
Rule 1. Pet Peeves
However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted:
Rule 2. Other Recommendations
If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator:
The following fails rule 2.
myarray[x/3+2:x/2+3:2]
myarray[x/3+2:x/2+3:2]
myarray[x/3+2 : x/2+3 : 2]
myarray[x/3+2: x/2+3: 2]
So the answer is,
myarray[x/3 + 2 : x/2 + 3 : 2]
Black Playground link Bug
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With