1,105,229 Community Members

double slice

Member Avatar
shanenin
Posting Whiz in Training
229 posts since May 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 29 [?]
Skill Endorsements: 1 [?]
 
0
 

I can't seem to see how this slice works

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

any insite would be helpful

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
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

Member Avatar
shanenin
Posting Whiz in Training
229 posts since May 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 29 [?]
Skill Endorsements: 1 [?]
 
0
 

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

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
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]

?

Member Avatar
shanenin
Posting Whiz in Training
229 posts since May 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 29 [?]
Skill Endorsements: 1 [?]
 
0
 

I figured correctly and verified with the interpreter.

now very clear. I appreciate your help :-)

Member Avatar
Gribouillis
Posting Maven
3,452 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 883 [?]
Skill Endorsements: 18 [?]
Moderator
 
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
Member Avatar
shanenin
Posting Whiz in Training
229 posts since May 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 29 [?]
Skill Endorsements: 1 [?]
 
1
 

I was working on this. I think i got the basics of slicing understood. by the way, for a beginner, udacity it pretty cool!

http://www.udacity.com/view#Course/cs101/CourseRev/apr2012/Unit/671054/Nugget/964001

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