List Indexing and Slicing
Imagine you have a row of lockers. To find your books, you need the locker number! In Python, we call these locker numbers Indexes. If you want to grab a whole row of lockers at once, we use Slicing.
What is List Indexing?
Indexing is used to access one specific item using its position number.
-
Zero-Based: In Python, the first item is always at index 0.
-
Negative Indexing: You can also count backward! The very last item in a list is at index -1.
What is List Slicing?
Slicing is used to cut out a specific "slice" or range of items from your list. It uses the colon (:) operator.
-
The Rule: Slicing includes the start index but stops right before the stop index (it is exclusive of the stop value).
Real-World Scenarios
-
Top Scores: Slicing the first 3 items to see the winners.
-
Last Song: Using index -1 to play the final track in a playlist.
-
Recent Items: Slicing the end of a list to see the most recent tasks.
How it Looks (Syntax & Examples)
The Pattern:
list[index] # Get one item
list[start:stop] # Get a range of items
Example 1: Basic Indexing
numbers = [10, 20, 30, 40]
print(numbers[1])
Output: 20
Example 2: Slicing a Range
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
Output: [20, 30, 40]
Summary:
-
Fast Access: Indexing is the fastest way to grab a single value.
-
New Lists: Slicing doesn't change the original list; it creates a new smaller list.
-
Be Careful: If you try to access an index that doesn't exist, Python will give you an "IndexError."