Indexing & Slicing
Indexing and slicing are fundamental operations to interact with data in Python's list and tuple data structures, allowing precise access to individual elements or subsequences.
Direct Access: Positive and Negative Indexing
Accessing individual elements within a sequence is done through indexing. Python supports two primary ways to index: positive indexing and negative indexing. Positive indexing starts from the beginning of the sequence, with the first element at index 0.
Negative indexing, conversely, starts from the end of the sequence. The last element is at index -1, the second to last at -2, and so on. This approach is particularly useful when you need to access elements relative to the end of a sequence without knowing its exact length.
Python, like many programming languages, uses 0-based indexing. This means the first element of any sequence is at index 0, not 1. This is a common source of off-by-one errors for new programmers.
data = [10, 20, 30, 40, 50], what is the result of data[-4]?Extracting Ranges: Basic Slicing
Slicing allows you to extract a subsequence, or a portion, of a list or tuple. The basic syntax for slicing is [start:stop] . Here, start is the index where the slice begins (inclusive), and stop is the index where the slice ends (exclusive).
This means the element at the stop index is not included in the resulting slice. The slice operation always returns a new sequence of the same type as the original, containing the elements from start up to, but not including, stop .
Flexible Slicing: Defaults and Steps
Slicing offers even more flexibility by allowing you to omit start or stop indices, or by adding a step parameter. If start is omitted, it defaults to the beginning of the sequence (index 0). If stop is omitted, it defaults to the end of the sequence.
The optional third parameter, step , determines how many elements to skip between each item in the slice. A step of 2, for example, would select every second element. A negative step value can be used to traverse the sequence in reverse order, which is a concise way to reverse a list or tuple.
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], write code to perform the following slicing operations:
1. Extract elements 'c' through 'g' using positive indices.
2. Get the last four elements using negative indices.
3. Reverse the entire list using slicing.
4. Extract every third element starting from the second element (index 1).my_list[::3] for my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]?Indexing & Slicing: Lists vs. Tuples
The syntax for indexing and slicing is identical for both lists and tuples in Python. You use square brackets [] with indices or slice notation for both data types. However, a critical difference arises from their fundamental characteristic: mutability.
Lists are mutable, meaning their elements can be changed after creation. Tuples are immutable, meaning their elements cannot be changed once the tuple is created. While you can extract elements or subsequences from a tuple using indexing and slicing, you cannot use these operations to modify the tuple's contents in place.
Remember that tuples are immutable. While you can use indexing and slicing to read elements or create new tuples from parts of an existing one, you cannot use assignment with [] to change individual elements within an existing tuple. This will always result in a TypeError.
Python sequences (lists, tuples) use 0-based indexing, where the first element is at index 0.
Positive indexing accesses elements from the start (0, 1, 2...), while negative indexing accesses from the end (-1, -2, -3...).
Slicing extracts subsequences using
[start:stop:step]notation.The
stopindex in slicing is exclusive, meaning the element atstopis not included in the result.Omitting
startorstopdefaults to the beginning or end of the sequence, respectively;[::-1]reverses a sequence.Indexing and slicing syntax is identical for lists and tuples, but only lists are mutable and can be modified via assignment.