Lists allow you to access individual elements and sublists (or “slices”) through indexing and slicing. Here’s an overview of how these work:
Each element in a list is associated with an index number, starting from 0
for the first element. You can access elements directly by specifying their index in square brackets.
# Example list
fruits = ['apple', 'banana', 'cherry', 'date']
# Accessing the first element
print(fruits[0]) # Output: 'apple'
# Accessing the third element
print(fruits[2]) # Output: 'cherry'
Python also supports negative indexing, where -1
refers to the last element, -2
to the second-to-last, and so on.
# Accessing the last element
print(fruits[-1]) # Output: 'date'
# Accessing the second-to-last element
print(fruits[-2]) # Output: 'cherry'
Slicing allows you to retrieve a range of elements from a list. This is done using the syntax list[start:stop:step]
, where:
To extract a portion of a list, specify the start and stop indices.
# Get elements from index 1 to 3 (excluding index 3)
print(fruits[1:3]) # Output: ['banana', 'cherry']
If you omit the start
or stop
indices, Python assumes you mean from the beginning or to the end of the list, respectively.
# Get all elements from the beginning to index 2 (exclusive)
print(fruits[:2]) # Output: ['apple', 'banana']
# Get all elements from index 1 to the end
print(fruits[1:]) # Output: ['banana', 'cherry', 'date']
The step value allows you to specify the interval between elements.
# Get every second element
print(fruits[::2]) # Output: ['apple', 'cherry']
# Reverse the list
print(fruits[::-1]) # Output: ['date', 'cherry', 'banana', 'apple']
start:stop:step
to extract sublists and customize intervals.