slice() function returns a new slice object you can use to slice over sequences such as lists, strings, or tuples.
Read more about lists in our full tutorial about Python Slicing.
Example 1: Slice with Stop Argument
One of the best way to learn is by example! Here are some examples of how to use the
slice() built-in function.
First, let’s create a list of 20 elements using the
>>> lst =list(range(20)) >>> lst [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
The list consists of all elements from 0 to 19 (included). You can now access the first ten elements of this list by creating a new slice object with stop index 10, and pass the newly-created slice into the indexing scheme using the square bracket notation
>>> s = slice(10) >>> lst[s] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Slice with Start and Stop Arguments
You can also give the start argument to start from any other position in the sequence to be sliced:
>>> lst =list(range(20)) >>> s = slice(5, 10) >>> lst[s] [5, 6, 7, 8, 9]
Example 3: Extended Slice with Start, Stop, and Step Arguments
The most advanced way is called extended slicing, where you define the start index, the stop index, and the step size:
>>> lst =list(range(20)) >>> s = slice(2, 10, 2) >>> lst[s] [2, 4, 6, 8]
You can use the
slice() method with up to three arguments:
Syntax: There are three ways of using the constructor: # 1. Create new slice that goes from start index 0 (default) to stop using default step size 1. slice(stop) # 2. Create new slice that goes from start index to stop using default step size 1. slice(start, stop) # 3. Create new slice that goes from start to stop using step as step size. slice(start, stop, step)
What’s the Purpose of slice() vs Python’s slicing notation?
Python also allows a more concise way of slicing sequences: the default slicing notation. Let’s quickly recap it:
Slicing is a concept to carve out a substring from a given string. Use slicing notation
s[start:stop:step] to access every
step-th element starting from index
start (included) and ending in index
stop (excluded). All three arguments are optional, so you can skip them to use the default values (
step=1). For example, the expression
s[2:4] from string
'hello' carves out the slice
'll' and the expression
s[:3:2] carves out the slice
You can either create a slice object explicitly using
slice() or you create it implicitly using the slice notation. Both variants are semantically identical:
>>> customers = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank'] >>> customers[1:5:2] ['Bob', 'Dave'] >>> customers[slice(1, 5, 2)] ['Bob', 'Dave']
There’s only one difference: if you use
slice() explicitly to create a slice object, you can reuse it for further slicing operations.
Performance Evaluation: Slicing vs slice()
This has some performance benefits, for example, when using the same slicing operation on different lists in a loop:
import time lst = [list(range(10000)), list(range(20000)), list(range(30000))] # Method 1: Slicing Notation start = time.time() for l in lst: print('Size of slice: ', len(l[5:-5:4])) print(time.time() - start) # Method 2: slice() Object start = time.time() s = slice(5, -5, 4) for l in lst: print('Size of slice: ', len(l[s])) print(time.time() - start)
Both methods have the same output:
Size of slice: 2498 Size of slice: 4998 Size of slice: 7498 0.03080606460571289 Size of slice: 2498 Size of slice: 4998 Size of slice: 7498 0.015621423721313477
However, the performance difference in this example is significant.
- Method 1 takes 0.03 seconds to complete.
- Method 2 takes 0.015 seconds to complete.
Using the function
slice() to create a slice object once in advance results in a 50% runtime performance reduction compared to using standard slicing. The reason is that standard slicing will internally recreate the same slice object in each iteration which is inefficient.
Interactive Shell Exercise: Understanding slice()
Consider the following interactive code:
Exercise: Guess the output before running the code.
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners
slice(stop): create a new slice that goes from start index 0 (default) to stop using default step size 1.
slice(start, stop): create a new slice that goes from start index to stop using default step size 1.
slice(start, stop, step): create a new slice that goes from start to stop using step as step size.
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.