Difference between indexing and slicing in Python
In Python, indexing and slicing are two ways to access individual or multiple items from a sequence object, such as a string, list, or tuple. While both indexing and slicing are used to extract a portion of the sequence, there are subtle differences between them. In this article, we will explore the differences between indexing and slicing in Python and provide examples of how to use each method.
Indexing
Indexing is a way to access a specific item from a sequence by its position, or index, in the sequence. In Python, indexing starts from 0, meaning the first item in the sequence has an index of 0, the second item has an index of 1, and so on.
To index a sequence in Python, we use square brackets []
and specify the index of the item we want to access. The syntax for indexing is as follows:
sequence[index]
Here, sequence
is the name of the sequence we want to index, and index
is the position of the item we want to access.
Let’s take an example of indexing a string in Python:
string = "hello"
print(string[1])
Output:
'e'
In this example, we created a string variable string
that contains the word “hello”. We then used indexing to access the second character of the string, which has an index of 1. The output of the code is the character ‘e’.
We can also use negative indexing in Python to access items from the end of the sequence. Negative indexing starts from -1, meaning the last item in the sequence has an index of -1, the second last item has an index of -2, and so on.
Let’s take an example of negative indexing in Python:
string = "hello"
print(string[-1])
Output:
'o'
In this example, we used negative indexing to access the last character of the string, which has an index of -1. The output of the code is the character ‘o’.
Index Error
One important thing to keep in mind while indexing a sequence is that if we try to access an index that does not exist, Python raises an IndexError
exception.
Let’s take an example of accessing an invalid index in Python:
string = "hello"
print(string[10])
Output:
IndexError: string index out of range
In this example, we tried to access the item at index 10 of the string, which does not exist. Python raised an IndexError
exception, indicating that the index is out of range.
Slicing
Slicing is a way to access a portion of a sequence object by specifying a range of indices. In Python, slicing is done using the :
operator inside the square brackets []
. The syntax for slicing is as follows:
sequence[start:stop:step]
Here, sequence
is the name of the sequence we want to slice, start
is the index of the first item we want to include, stop
is the index of the first item we want to exclude, and step
is the number of items we want to skip between each included item.
If we omit the start
index, Python assumes it to be 0. If we omit the stop
index, Python assumes it to be the length of the sequence. If we omit the step
value, Python assumes it to be 1.
Let’s take an example of slicing a list in Python:
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])
Output:
[2, 3, 4]
In this example, we created a list numbers
that contains the integers from 1 to 5. We then used slicing to extract a portion of the list starting from the second item and ending at the fourth item. The output of the code is the list [2, 3, 4]
.
We can also use negative indices and step values in Python while slicing a sequence.
Let’s take an example of slicing a string with negative indices and step values in Python:
string = "hello world"
print(string[6:-1:2])
Output:
'wrd'
In this example, we used slicing to extract a portion of the string starting from the seventh character and ending at the second last character, with a step value of 2. The output of the code is the string 'wrd'
.
Slice Assignment
One interesting feature of slicing in Python is called slice assignment, which allows us to replace a portion of a sequence with anew sequence. To perform slice assignment, we use the same syntax as slicing, but on the left-hand side of an assignment operator =
.
Let’s take an example of slice assignment in Python:
numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [6, 7, 8]
print(numbers)
Output:
[1, 6, 7, 8, 5]
In this example, we used slicing to replace a portion of the list numbers
starting from the second item and ending at the fourth item with a new list [6, 7, 8]
. The output of the code is the modified list [1, 6, 7, 8, 5]
.
Out of Range Slicing
Similar to indexing, if we try to slice a sequence with an invalid range of indices, Python does not raise an error, but instead returns an empty sequence.
Let’s take an example of slicing with an invalid range in Python:
numbers = [1, 2, 3, 4, 5]
print(numbers[5:8])
Output:
[]
In this example, we tried to slice a list numbers
starting from the sixth item and ending at the eighth item, which do not exist in the list. Instead of raising an error, Python returned an empty list, indicating that there are no elements in the specified range in the list.
Conclusion
In this article, we explored the differences between indexing and slicing in Python. Indexing is a way to access a specific item from a sequence object by its position, while slicing is a way to access a portion of a sequence by specifying a range of indices. While both indexing and slicing are useful techniques to extract information from sequences, they are applied in different contexts depending on the problem at hand. By understanding the differences between indexing and slicing in Python, we can write more efficient and concise code and build better data manipulation and analysis tools.