How to Use Double Colon (::) in List in Python (3 Examples)
In this article, you’ll learn how to use the double colon in a Python list.
The table of content is shown below:
Let’s start right away!
Create Example List
At the start, we will create a demo Python list that we will use in the examples below. Take a look at the following code.
my_list = [1, 2, 3, 4, 5, 6, 7, 8] print(my_list) # [1, 2, 3, 4, 5, 6, 7, 8]
As you can see in the previous output, we have created my_list
, a list object that contains eight integers. Let’s see how to use the double colon with it!
Example 1: Use Double Colon to Slice List
The double colon is commonly used for slicing. In my_list
, it can be used to extract a portion of the list based on the specific start, stop, and step values.
sliced_list = my_list[2:7:2] print(sliced_list) # [3, 5, 7]
In this example, we start slicing from index 2, stop at index 7, and select every second element. Thus, the resulting sliced_list
contains the [3, 5, 7]
values.
Example 2: Use Double Colon to Reverse List
The double colon can also be used to reverse a list. We just have to omit the start and the stop values while specifying a negative step size.
reversed_list = my_list[::-1] print(reversed_list) # [8, 7, 6, 5, 4, 3, 2, 1]
Here, my_list[::-1]
starts from the beginning of my_list
, stops at the end, and select elements with a step size of -1, resulting in reversed_list
.
Example 3: Use Double Colon to Skip Elements in List
When slicing a list, we can use the double colon to skip elements.
skipped_list = my_list[::2] print(skipped_list) # [1, 3, 5, 7]
Take a look at the above code snippet. The slice [::2]
selects elements starting from the beginning, stopping at the end, and with a step size of 2, resulting in skipped_list
as you can see.
Video, Further Resources & Summary
Do you need more explanations on how to use the double colon in a list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
The YouTube video will be added soon.
Furthermore, you could have a look at some of the related on Statistics Globe:
- Learn Python Programming Language
- How to Compare Two Lists in Python
- Convert List to Sequence of Variables in Python
- Lists in Python (13 Examples)
- Find Substring within List of Strings in Python
- Group List into Sublists in Python
This post has shown how to use the double colon in a list in Python. In case you have additional questions, please let me know in the comments section below.
This page was created in collaboration with Paula Villasante Soriano. Please have a look at Paula’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.
Statistics Globe Newsletter