Python Data Structures: Indexing and Slicing

Python has various built-in data structures such as tuples, lists, dictionaries, and sets. Like a variable, python data structures are also used to store a value. Unlike a variable, they don’t just store a value, rather a collection of values in various formats.

Some of Data Structures we will cover in this Blog are:-

  • Indexing and Slicing
  • Array
  • Tuples
  • Lists
  • Dictionaries
  • Sets
  • Stacks and Queues

Indexing and Slicing

A string can be thought of as a sequence of characters. Similarly, python data structures store sequences of objects (floats, integers, strings, etc.).

Consider a sequence of 10 characters ranging from A to J where we assign a unique position to each literal in a sequence. The position assigned to each character is a sequence of integers beginning with 0 up to the last character. These increase successively by 1 as can be seen below.

Index0123456789
SequenceABCDEFGHIJ

In the above sequence, the character A is at index 0B at 1C at 2, and so on. Notice how the index increases in chronological order by one unit at each step. Whenever a new character is appended to this sequence, it will be appended at the end and will be assigned the next index value (in the above example, the new index will be 10 for the new character). Almost all python data structures have an index to position and locate the element.

Elements within the sequence can be accessed using the square brackets []. It takes index of an element and returns the element itself. The syntax for accessing a single element is as follows:

sequence[i]

The above statement will return the element from sequence at index i. We can access multiple elements from the sequence using the syntax [start index : end index] in the following manner:

sequence[si : ei]

The above statement will return values starting at index si up to but NOT including the element at index ei. This operation is referred to as slicing. For example:

sequence[0:4] will return elements from 'A' to 'D' and not up to 'E'. Element at the last index in the provided range will not be returned.

Python also supports negative indexing to access elements from the sequence end and it starts with -1 as follows:

Index0123456789
SequenceABCDEFGHIJ
Negative Index-10-9-8-7-6-5-4-3-2-1

A sequence can also be sliced using the negative indexing. In order to access the last element, we write

sequence[-1]

and it will return the element J. Similarly, a range can be provided to access multiple elements.

sequence[-5:-1] will return elements from 'F' to 'I'

That’s all for now we’ll continue in the next blog…

Leave a Comment

Your email address will not be published. Required fields are marked *