Dive into INDEXING vs SLICING in Python

Image Source: Author

Most of us must be wondering why I have come up with this. I guess I am right. Ain’t I? While doing the project I got stuck on a couple of pretty basic use cases. So after poking around a bit to get un-stuck, I figured it was worth sharing what I learned.

Definition :

Indexing: Indexing is a technique used to obtain an individual element in the iterable by its position within the iterable.

Slicing: Slicing is a technique that takes elements from one given index to another given index.

INDEXING

They are basically used for Python Sequences types like list, string, tuple, range objects. Lists are “ZERO indexed” and so indexing starts from the zeroth position. In any Sequence, the zeroth position refers to the first element of it. Negative indexing refers to indexing in reverse order. -1 refers to the last element of the sequence.

Indexing in String
Indexing in String
Indexing in String
Indexing in List

SLICING

They are basically used for Python Sequences types like list, string, tuple, range objects. Starts from the start position and stops at the end position. It returns elements within the given interval. The output contains the element from the start position to a position before the actual end position. Negative slicing refers to the start slicing from the end position.

Image Source: Author

I know that here you must have got confused, just have a look at the examples given below:

Few Special feature of slicing :

[:] refers to complete duplication of the given sequence

[m:] refers to the element set from the start position i.e m here to the end of the given sequence.

[:n] refers to the element set from the start of the given sequence to the given end position i.e n.

STEP in Slicing: Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

Hope the article helps you out and clears your basic concepts.

Thank You !!

3rd year CSE student at IIITKALYANI , enthusiastic learner and explorer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store