Slicing in python


Slicing

Slicing extracts a subset of elements from a sequence. In python, elements are sliced based on their index in the stream. As a sequence(List, tuple, and string) is an ordered stream of data, it can be indexed and sliced while a collection(Set and dictionary) is an unordered stream of data, thus they can’t be indexed and sliced. Slicing is one of the most powerful and useful feature in python. It helps in abstracting a certain part of sequences that needs to be focused rather than the whole sequence. This aids readability.

Slicing is just like indexing, but rather than returning an element of a sequence, it returns a part of a sequence. It mainly uses three parameters enclosed in square brackets []:

Sequence[ start : stop : step ]

  • start: Starting index where the slicing of sequence starts. By default value is 0. 
  • stop: Ending index where the slicing of sequence stops+1. By default value is len(Sequence).
  • step: Integer value which determines the increment between each index for slicing. By default value is 1.

Usage of start, stop, and step parameters is optional. Python uses negative indexes to represent positions from the end of the sequence. A reverse subsequence is obtained by using a negative step and by switching the start and end indices.

Examples-:

Special cases-:

Slice()

Slice() is a constructor that creates a slice object to represent the set of indexes(start, stop, step). These slice objects are passed to sequences as indexes for slicing. The syntax of slice() is:

slice(start(optional), stop, step(optional))

When only one parameter value is provided, it takes it to be the stop value since the stop parameter is mandatory to provide in slice function. The default value of start and stop parameters is None. Slice function allows easy creation of a stepwise sub-sequence without doing a complete iteration on the existing sequence.

Creating a slice object in python

Slicing using slice object

Python slice object has no use on its own, it’s useful when used in conjunction with sequences to create a sub-sequence.

 

Add Comment

%d bloggers like this: