1

Possible Duplicate:
Good Primer for Python Slice Notation

I first ran across it last night for reversing a string "Hello"[::-1] and I can't figure out how it actually works.

"Hello"[::-1] # returns "olleH"
[1,2,3,4,5][::-1] # returns [5,4,3,2,1]
"Hello"[1:5:1] # returns "ello"
"Hello"[1:5:2] # returns "el"

My searches for "third expression in python index" have come up empty. What is this expression and how does it work. Obviously ::-1 reverses the list but I can't figure out what the other, positive values represent.

Community
  • 1
  • 1
pdizz
  • 4,100
  • 4
  • 28
  • 42
  • 4
    See here: http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation – Gerrat May 17 '12 at 15:29

2 Answers2

2

Actually the third optional argument is called step or stride. It's default value is 1.

>>> 'hello'[::] # here the value of stride is 1, means take a step of one between two indexes
'hello'   

>>> 'hello'[::2] #take a step of 2 so starting from h -->l --> o 
'hlo'

>>> 'abcdef'[::-1] #negative step actually means 'abcdef'[-1:-len('abcdef')-1:-1]
'fedcba'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

In the last example, these are the characters that matches the step = 2.

"Hello"[1:5:2] # returns "el"
  ^ ^
greut
  • 4,305
  • 1
  • 30
  • 49