List Slicing in Python
List slicing in Python allows you to extract a portion (slice) of a list, creating a new list containing only the selected elements. It is a concise way to access and manipulate parts of a list without modifying the original list.
Syntax
list[start:stop:step]
start
(Optional) : The index where the slice starts (inclusive). If omitted, it defaults to 0
, meaning the slice starts at the beginning of the list.
end
(Optional): The index where the slice stops (exclusive). The element at this index is not included in the slice. If omitted, it defaults to the length of the list, effectively slicing to the end of the list.
step
(Optional): It determines the interval between elements included in the slice. If omitted, it defaults to 1
. A negative step
value allows you to create a reversed slice.
Examples
Basic Slicing
You can extract a specific range of elements from a list by specifying the start
and stop
indices. The slice includes the element at start
index but excludes the element at stop
index.
my_list = [5, 10, 15, 20, 25, 30]
new_list = my_list[1:4]
print(new_list) # Output: [10, 15, 20]
Indices in Python start at the position 0
, meaning the first element is at the index 0
, the second element is at the index 1
and so on.
Omitting the start parameter
If you omit the start
parameter, the slice begins at the start of the list. This is equivalent to setting start
to 0
.
my_list = [5, 10, 15, 20, 25, 30]
new_list = my_list[:4]
print(new_list) # Output: [5, 10, 15, 20]
Omitting the end parameter
If you omit the end
parameter, the slice continues until the end of the list.
my_list = [5, 10, 15, 20, 25, 30]
# Slice elements from index 2 to the end of the list
new_list = my_list[2:]
print(new_list) # Output: [15, 20, 25, 30]
Using negative indices
List slicing also supports negative indexing, which allows you to count elements from the end of the list. The last element is indexed as -1
, the second to last as -2
, and so on.
my_list = [5, 10, 15, 20, 25, 30]
new_list = my_list[-5:-2]
print(new_list) # Output: [10, 15, 20]
Step parameter
The step
parameter controls the interval between elements in the slice.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = my_list[1:6:2]
print(new_list) # Output: [2, 4, 6]
You can use a negative step
parameter to reverse a list.
my_list = [5, 10, 15, 20, 25, 30]
new_list = my_list[::-1]
print(new_list) # Output: [30, 25, 20, 15, 10, 5]
Since both start
and stop
parameters are omitted, the slice considers the entire list.
The step -1
means the slicing will traverse the list in reverse order, starting from the last element and moving backward to the first.
This creates a new list where the elements of the my_list
are reversed.
Omitting all parameters
If all parameters are omitted, the slice returns a copy of the entire list.
my_list = [5, 10, 15, 20, 25, 30]
new_list = my_list[:]
print(new_list) # Output: [5, 10, 15, 20, 25, 30]