PythonPython Data TypesIndexing in Sequencial Data Types

Indexing and Slicing in Python

In Python, many data types are sequences, which means they are ordered collections of items. The most common sequence types are strings, lists, and tuples. To work effectively with these sequences, you need to know how to access their elements. This is done through indexing (accessing a single element) and slicing (accessing a subsequence of elements).

Indexing: Accessing Single Elements

Every element in a sequence has a position, called an index. Python uses a zero-based indexing system.

Indexing in Python

Python supports two types of indexing:

Positive (Forward) Indexing

  • Starts from 0 for the first element.
  • The second element is at index 1, the third at 2, and so on.
  • The last element is at index length - 1.
my_string = "Python"
# P  y  t  h  o  n
# 0  1  2  3  4  5
 
print(my_string[0]) # Output: P
print(my_string[4]) # Output: o

Pyground

Given the list `my_list = [10, 20, 'a', 'b', True]`, access the first element, the last element, and the middle element ('a').

Expected Output:


First element: 10
Last element: True
Middle element: a

Output:

💥

IndexError: If you try to access an index that is outside the valid range of the sequence (e.g., index 6 in the string "Python"), Python will raise an IndexError.

Slicing: Accessing Subsequences

Slicing is a powerful feature that lets you extract a portion (a “slice”) of a sequence. The syntax is [start:stop:step].

  • start: The index where the slice begins (inclusive). If omitted, defaults to 0.
  • stop: The index where the slice ends (exclusive). The slice goes up to, but does not include, this index. If omitted, defaults to the end of the sequence.
  • step: The amount to increment by. If omitted, defaults to 1.

Basic Slicing

Extracts a simple range of elements.

my_list = [0, 1, 2, 3, 4, 5, 6, 7]
 
# Elements from index 2 up to (but not including) index 5
sub_list = my_list[2:5] 
print(sub_list) # Output: [2, 3, 4]

Pyground

Given the string `s = "abcdefghij"`, perform the following operations: 1. Get the characters from index 2 to 5. 2. Get the last 4 characters. 3. Get the entire string backwards.

Expected Output:


Slice [2:5]: cde
Slice [-4:]: ghij
Reversed: jihgfedcba

Output:

Slicing is forgiving! If you provide start or stop indices that are out of bounds, Python will not raise an error. It will simply return an empty sequence or go to the boundary of the existing sequence.