Python
  • Initial page
  • Skills & Concept
    • Function
    • Generator
    • Class
    • Asyncio
    • Interface
    • Decorator
    • Maxin
    • Abstract Base Class
    • MemoryView
  • Magic methods
    • What is Magic Methods?
  • Data Structure
    • Data Structure in Python
    • List & Tuple
    • Named Tuples
    • Slicing in Sequence
    • Queue & Dequeue
    • Ordered Dict
    • Linked list
  • Writing Test Case
    • How to write Test case
    • Testing a Flask End-point
  • Libraries
    • Flask and Gunicorn
      • Flask JWT
      • Flask Limiter
      • Flask Rest
Powered by GitBook
On this page

Was this helpful?

  1. Data Structure

Slicing in Sequence

The Pythonic convention of excluding the last item in slices and ranges works well with the zero-based indexing used in Python, C and many other languages.

# Given the list below
l  =  [10,20,30,40,50,60]
# index 0  1  2  3  4  5
print(l[:2]) # start at index 0, stop at index 2
>>> 10, 20
print(l[2:]) # start at index 2, no stop -> retrieve all, starting from index 2
>>> 30, 40, 50, 60
print(l[:3]) # start at index 0, no stop and step is 3: 0, 0+3, 3+3 etc.
>>> 10, 40
print(l[3::2]) # start at index 3, no stop and step is 2: 3, 3+2 etc.
>>> 40, 60

The stride/step can also be negative, returning items in reverse

s = "bicycle"
print(s[::3])
>>> 'bye'
print(s[::-1]) # negative step: bicycle -> elcycib
>>> 'elcycib'
print(s[::-2]) # negative step: bicycle -> elcycib, and step 2 -> eccb
>>> 'eccb'

# start at 3: bic<-y->cle
# No stop
# step in negative 2, ycib, index 0, 0+2, i.e. y then i
print(s[3::-2])
>>> 'yi'

# start at 5: bicyc<-l->e
# stop at 2: cycl
# step in negative 2 (reverse search and skip 2): cycl -> lcyc ->index 0, 0+2, ly
# step in negative 2, bic<-y, i.e. y then i
print(s[5:2:-2]) 
>>> 'ly'

To evaluate the expression seq[start:stop:step], Python calls seq.__getitem__(slice(start, stop, step))

Slice Object contains indice, start, stop, step

The slice() constructor creates a Slice object representing the set of indices specified by range(start, stop, step)

The [ ] operator can also take multiple indexes or slices separated by commas. The __getitem__ and __setitem__ special methods that handle the [] operator simply receive the indices in a[i, j] as a tuple. In other words, to evaluate a[i, j], Python calls a.__getitem__((i, j)).

The built-in sequence types in Python are one-dimensional, so they support only one index or slice, and not a tuple of them.

Multidimensional Slicing and Ellipsis

PreviousNamed TuplesNextQueue & Dequeue

Last updated 6 years ago

Was this helpful?

For example, slice(1, 5, 2) contains the indice with (1, 3) –

Reference