Python List Slicing
List slicing in Python allows extracting specific parts of a list by specifying a start index, an end index, and an optional step. Slicing helps access a subset of elements without modifying the original list.
List slicing follows the syntax:
list[start:end:step]
start
: The index where slicing begins (inclusive).end
: The index where slicing stops (exclusive).step
: The interval between elements (optional, default is 1).
Examples
1. Basic List Slicing
Extracting a sublist using start
and end
indices.
# Defining a list of numbers
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
# Slicing from index 2 to 5 (excluding index 5)
sublist = numbers[2:5]
# Printing the sliced list
print("Sliced List:", sublist)
We define a list numbers
containing integers. Using numbers[2:5]
, we extract elements from index 2 to 4 (index 5 is excluded). The extracted sublist contains [30, 40, 50]
.
Output:
Sliced List: [30, 40, 50]
2. Slicing with a Step
Extracting every second element using a step value.
# Defining a list of letters
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
# Slicing with a step of 2
alternate_letters = letters[::2]
# Printing the result
print("Every Second Element:", alternate_letters)
We define a list letters
. The slice operation letters[::2]
extracts every second element, starting from index 0, resulting in ['A', 'C', 'E', 'G']
.
Output:
Every Second Element: ['A', 'C', 'E', 'G']
3. Slicing with Negative Indices
Extracting elements from the end using negative indices.
# Defining a list of colors
colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange']
# Slicing the last three elements
last_three = colors[-3:]
# Printing the result
print("Last Three Colors:", last_three)
We define a list colors
and use colors[-3:]
to slice the last three elements, which gives ['yellow', 'purple', 'orange']
.
Output:
Last Three Colors: ['yellow', 'purple', 'orange']
4. Reversing a List Using Slicing
Using a negative step to reverse a list.
# Defining a list of words
words = ["Python", "Java", "C++", "JavaScript"]
# Reversing the list using slicing
reversed_words = words[::-1]
# Printing the result
print("Reversed List:", reversed_words)
We define a list words
. The slice words[::-1]
starts from the end and moves backward with a step of -1, effectively reversing the list.
Output:
Reversed List: ['JavaScript', 'C++', 'Java', 'Python']
Conclusion
- Basic slicing: Use
list[start:end]
to extract a sublist. - Step slicing: Use
list[start:end:step]
to extract elements with intervals. - Negative indices: Use
-1
to access elements from the end. - Reverse slicing: Use
list[::-1]
to reverse a list.