1.11M Members

double slice

 
0
 

I can't seem to see how this slice works

test = (1,2,3)
>>> test[::2]
(1, 3)

any insite would be helpful

 
0
 

The Python's slicing operator can be used with any indexed sequence like strings, lists, ...
syntax --> seq[begin : end : step]
step is optional
defaults are index begin=0, index end=len(seq)-1, step=1
step = -1 reverses sequence

 
0
 

still haveing trouble understanding it :-) in my example what are the start, stop and reverse sequence

 
0
 

in sequence (1, 2, 3)[::2]
the start is element 1
the end is element 3
and step is 2 so it skips the second element (happens to be 2)

Perhaps this gives more insight ...

>>> (1,2,3,4,5,6,7,8)[::2]
(1, 3, 5, 7)
>>>

Even though 8 is the end it gets skipped by step=2

What do you think would be the result of ...

(1,2,3,4,5,6,7,8,9)[::-2]

or

(1,2,3,4,5,6,7,8)[::-2]

?

 
0
 

I figured correctly and verified with the interpreter.

now very clear. I appreciate your help :-)

 
0
 

There is a way to ask python what are start, stop and step:

>>> s = slice(None, None, -2) # a slice object corresponding to [::-2]
>>> s.indices(8)
(7, -1, -2) # start, stop, step if the slice is applied to a tuple of length 8
Question Answered as of 1 Year Ago by vegaseat and Gribouillis
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article