In Python, indexing is a way to directly access individual elements within an iterable object, such as strings, lists, or tuples. By using an index or indices, you can point to a specific element and extract its values.
Similarly, slicing allows you to extract or access a range of elements or subparts from an iterable object efficiently. With slicing, you can reverse sequences, skip elements, or create subsets of data without writing complex loops.
Understanding indexing and slicing is not just about accessing elements; it helps you write efficient, readable, and scalable Python code.
Table of Contents
What is indexing?
Indexing is the process of extracting or accessing an individual element from iterable objects, such as strings, lists, and tuples. An index is a numerical value that represents the position of an element within a sequence. Think of it as a unique number given to each element in a collection to identify its position.
A string is a sequence of characters stored in continuous memory locations. Each character in the string has a specific position, called an index, which help you access individual characters easily.
For example, suppose you have a string “PYTHON”:
Python uses zero-based indexing, meaning the first element of a sequence is assigned the index 0
instead of 1
. This means that for any ordered collection, like strings, lists, or arrays, the counting starts from 0
and not from 1
.
Python supports two types of indexing: forward indexing and backward indexing.
Forward Indexing (Left to Right)
Forward indexing starts from the leftmost character and uses positive numbers, start with 0
. For example, in the string "PYTHON"
, the character 'P'
is at index 0
, 'Y'
is at index 1
, and so on till the last character of string. This helps in getting characters quickly based on their positions.
Backward Indexing (Right to Left)
This is also known as Negative indexing. Backward indexing allows you to access characters from the right end of the string using negative numbers. The last character is indexed as -1
(not 0
), the second last as -2
, and so on till the first character of the string. For example, in the string "PYTHON"
, the character 'N'
is at index -1
and at the same time, it is also at index 5
, while 'O'
is at index -2
and 4
. This method is particularly useful when working with the end of a string when you don’t know its exact length.
Important Notes:
- Strings are immutable, meaning you cannot modify their elements directly.
string_1 = 'Programming'
# string_1[0] = 'P' # This will raise an error
Python- Accessing an index beyond the length of the string raises an IndexError.
# string_1[100] # ❌ IndexError
PythonIndexing in Lists
However, you can modify list elements using indexing, as they are mutable. Lists are flexible collections that can store different data types, including numbers, strings, and other lists. Each element can also accessed using its index as we discussed above.
list1 = [10, 20, "A", "B", 5.5]
print(list1[1]) # Output: 20
print(list1[-2]) # Output: B
list1[2] = 30
print(list1) # Output: [10, 20, 30, 'B', 5.5]
PythonNested lists allow multi-level indexing.
nested_list = [1, 2, 3, [4, 5, 6], [7, 8, 9]]
print(nested_list[3][2]) # Output: 6
PythonIndexing in Tuples
Tuples are like lists but immutable, meaning once created, they cannot be modified. You can access individual elements using indexing.
tup1 = (2, 4, 6, 8, 10)
print(tup1[0]) # Output: 2
print(tup1[-1]) # Output: 10
PythonWhat is slicing?
Slicing is a technique used to extract a subset or a range of elements from an iterable, such as a string, list, or tuple. Unlike indexing, which retrieves only a single element, slicing allows retrieving a subset of elements using a defined pattern.
Syntax
data[start:end:step]
Pythonwhere,
- Start: Index where the slice start and this index value is included. (default is
0
) - End: Index where the slice ends and this index value is not included.
- Step: The gap between elements (default is 1).
For Example:
str1 = "Hello, Python"
print(str1[2:10:2]) # Output: lo y
PythonThe slice str1[2:10:2]
means “start at index 2, go up to index 10
(but not including 10
), and take every 2nd character”. So, it picks characters from the string starting from “l” at index 2, and continues picking every other character until it reaches the character at index 8, resulting in the output: lo y
.
# Slice from index 0 to 4 inclusive
print(str1[0:5]) # Output: Hello
# Slice from index 7 to the end
print(str1[7:]) # Output: Python
PythonKey Points:
If the start index is left empty, it defaults to 0
, meaning the slice starts from the very beginning of the sequence. If the end index is left empty, it defaults to the length of the string, meaning the slice goes all the way to the end of the sequence. Additionally, if a negative step is used, it reverses the order of the slice, effectively allowing you to retrieve characters in reverse order.
print(str1[::-1]) # Output: nohtyP ,olleH
PythonSlicing in Lists
Slicing helps extract sublists or modify list contents efficiently.
num1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from index 2 to 5
print(num1[2:6]) # Output: [2, 3, 4, 5]
# Slice with step of 2
print(num1[::2]) # Output: [0, 2, 4, 6, 8]
# Reverse the list
print(num1[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
PythonKey Points:
- Out-of-range slicing does not raise an error.
print(num1[:15]) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python- You can modify slices by replacing parts of a list.
num1[2:5] = [20, 30, 40]
print(num1) # Output: [0, 1, 20, 30, 40, 5, 6, 7, 8, 9]
PythonSlicing in Tuples
Since tuples are immutable, you can extract elements but cannot modify them.
data = (10, 20, 30, 40, 50, 60)
# Slice from index 1 to 3
print(data[1:4]) # Output: (20, 30, 40)
# Slice with step of 2
print(data[::2]) # Output: (10, 30, 50)
# Reverse the tuple
print(data[::-1]) # Output: (60, 50, 40, 30, 20, 10)
PythonConclusion
Indexing and slicing are essential for handling data structures like strings, lists, and tuples in Python. Whether you are a beginner or an experienced programmer, mastering these techniques will help you write clean, efficient, and professional Python code.