Master Python Slicing: From Basics to Advanced Tricks
This guide explains Python's slice() function, its syntax and parameters, and demonstrates how to use simple and advanced slicing techniques on lists, tuples, strings, and Unicode sequences with clear code examples.
What is slice()
The slice() function creates a slice object that can be used to specify start, stop, and step values when extracting subsections of sequence types such as lists, tuples, and strings.
Syntax
Two forms are supported:
slice(stop) slice(start, stop[, step])Parameters
start – the index where the slice begins (default None).
stop – the index where the slice ends (exclusive).
step – the interval between elements (default None).
Basic Example
Creating a slice that captures the first five elements:
myslice = slice(5)
print(myslice) # slice(None, 5, None)Applying it to a range object:
arr = range(10)
print(arr) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Using the slice
print(arr[myslice]) # [0, 1, 2, 3, 4]Loop vs. Slice
Instead of looping to print each element, slicing can produce the same result in a single statement:
for i in range(3):
print(arr[i])
# Output: 0 1 2
# Collecting values into a list
r = []
for i in range(3):
r.append(arr[i])
print(r) # [0, 1, 2]Using Colon Syntax
Python’s slice notation sequence[start:stop] is concise and expressive:
print(arr[0:5]) # [0, 1, 2, 3, 4]
print(arr[:5]) # same as above, start omitted
print(arr[1:5]) # [1, 2, 3, 4]Negative indices allow reverse slicing:
print(arr[-5:]) # [5, 6, 7, 8, 9]
print(arr[-5:-1]) # [5, 6, 7, 8]Edge Cases
If the start index is greater than the stop index, the result is an empty list:
print(arr[5:4]) # []Step Slicing
Adding a step value extracts elements at regular intervals:
# Every two elements from the first ten
print(arr[:10:2]) # [0, 2, 4, 6, 8]
# Every fifth element from a range of 100
arr = range(100)
print(arr[::5]) # [0, 5, 10, 15, ..., 95]Slicing Other Sequence Types
Tuples, strings, and Unicode strings also support slicing:
t = (1, 2, 3, 4)
print(t[:2]) # (1, 2)
s = 'abcde'
print(s[:2]) # 'ab'
u = u'我来了'
print(u[:2]) # u'\u6211\u6765'Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
