Extended Slices in Python

This is a reason why you should develop a program in Python. Python's syntax is one of the most simple and powerful grammar on the earth. I would like to introduce you to the extended slices.

>>> L = range(10)
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

List, tuple and string are accessible by given parameters.

  1. Begin index
  2. End index (optional)
  3. Step (optional)

For example, you may get an item using the first parameter.

>>> L[5]
5

The negative index means the index in reverse order.

>>> L[-1]
9
>>> L[-5]
5

If you want to obtain sub-list, you may use the second parameter.

>>> L[1:3]
[1, 2]
>>> L[-5:]
[5, 6, 7, 8, 9]
>>> L[1:-1]
[1, 2, 3, 4, 5, 6, 7, 8]

The interesting one is the third parameter to specify step of the result sub-list.

>>> L[1:8:2]
[1, 3, 5, 7]
>>> L:2
[0, 2, 4, 6, 8]

What if the step is negative?

>>> L:-1
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> s = 'abcdef'
>>> s:2
'ace'
>>> s:-1
'fedcba'

That's it! You may reverse a list or string by the extended slices.

Tags: ,

Post new comment