Slice a List
Python - Slice a List
To slice a List in Python, use slice() builtin function.
slice() builtin function returns a slice object. And we can use this slice object to slice a Python List. All we need to do is, pass the slice object as an index in the square brackets after the list variable. This expression returns the sliced list.
The following is a sample code snippet to slice a list with specific value for stop parameter in slice function.
list_object = []
slice_object = slice(stop)
result = list_object[slice_object]
The following is a sample code snippet to slice a list with specific value for start, stop and an optional step parameter in slice function.
list_object = []
slice_object = slice(start, stop[, step])
result = list_object[slice_object]
Examples
1. Slice List with specific end position
In this example, we will prepare a slice object with specific end/stop position stop=5
, and use this slice object to slice given list.
Python Program
list_1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
stop = 4 #end position of slice
slice_object = slice(stop)
result = list_1[slice_object]
print(result)
Output
['a', 'b', 'c', 'd']
The slice object would contain the indices [0, 1, 2, 3] for given stop value of 4. And the elements in the list corresponding to these indices are ['a', 'b', 'c', 'd']
. Hence the resulting list is ['a', 'b', 'c', 'd']
.
2. Slice List with specific start and end positions
In this example, we will prepare a slice object with specific start and stop positions, and use this slice object to slice given list.
Python Program
list_1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start = 2 #start position of slice
stop = 7 #end position of slice
slice_object = slice(start, stop)
result = list_1[slice_object]
print(result)
Output
['c', 'd', 'e', 'f', 'g']
The slice object would contain the indices [2, 3, 4, 5, 6] for given start and stop values. And the elements in the list corresponding to these indices are shall be returned by list_1[slice_object]
. Hence the resulting list of ['c', 'd', 'e', 'f', 'g']
.
3. Slice List with specific start and end positions, and a given step value
In this example, we will prepare a slice object with specific start and stop positions, and also a specific value for step. We shall then use this slice object to slice given list.
Python Program
list_1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start = 2 #start position of slice
stop = 7 #end position of slice
step = 2
slice_object = slice(start, stop, step)
result = list_1[slice_object]
print(result)
Output
['c', 'e', 'g']
The slice object would contain the indices [2, 4, 6]. And the elements in the list corresponding to these indices shall be returned by list_1[slice_object]
. Hence the resulting list of ['c', 'e', 'g']
.
Summary
In this tutorial of Python Examples, we learned how to slice a list, using slice() builtin function.