Problem Formulation: What does the double colon
sequence[3::4] mean in Python?
You can observe a similar double colon
:: for sequences:
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst[::2]
Answer: The double colon is a special case in Python’s extended slicing feature. The extended slicing notation
string[start:stop:step] uses three arguments
step to carve out a subsequence. It accesses every
step-th element between indices
start (included) and
stop (excluded). The double colon
:: occurs if you drop the
stop argument. In this case, Python will use the default value and doesn’t assume an artificial stop.
Here are some examples:
string[::2]reads “default start index, default stop index, step size is two—take every second element”.
string[::3]reads “default start index, default stop index, step size is three—take every third element”.
string[::4]reads “default start index, default stop index, step size is four—take every fourth element“.
string[2::2]reads “start index of two, default stop index, step size is two—take every second element starting from index 2“.
Let’s have a look at those examples in a Python code shell:
>>> s = 'hello world' >>> s[::2] 'hlowrd' >>> s[::3] 'hlwl' >>> s[::4] 'hor' >>> s[2::2] 'lowrd'
Background: 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 dive into our full slicing tutorial here:
Also, it may help to watch my introductory video on slicing:
To boost your Python skills, check out my free cheat sheets and code tutorials sent to you via email:
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. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, 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.