Problem Formulation: What does the double colon string[::2]
or sequence[3::4]
mean in Python?
>>> string[::2]
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 start
, stop
, and 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 (start=0
, stop=len(lst)
, 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 'hl'
.
You can dive into our full slicing tutorial here:
[Full Tutorial] Introduction to Slicing
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: