How to Use Colon (:) in List in Python (2 Examples)

 

In this tutorial, you’ll learn how to use the colon operator in a list in the Python programming language.

Here you have an overview of the tutorial:

Let’s dive right into the code!

 

Creation of Example Data

The first step in this tutorial will be to create a Python list to use as an example. Take a look at the code below.

my_list = [1, 2, 3, 4, 5]
print(my_list)
# [1, 2, 3, 4, 5]

As you can see, my_list is a list containing five integers. Let’s see how the colon operator can be useful in working with lists!

 

Example 1: Use Colon for Slicing or Extended Slicing

Slicing is a widely used method for extracting a portion of a list. The colon operator allows us to create a new list that contains a subset of elements from the original list.

sliced_list = my_list[1:4]
print(sliced_list)
# [2, 3, 4]

As shown in the example, the colon operator selected the elements from index 1 to index 4 (not including) in my_list, resulting in a new sliced_list.

The colon operator can also be combined with additional parameters to control the step size of the slice as follows.

sliced_list = my_list[1:4:2]
print(sliced_list)
# [2, 4]

Here, my_list[1:4:2] selected elements starting from index 1 up to (but not including) index 4, with a step size of 2. The resulting sliced list contains every second element.

 

Example 2: Use Colon for Iteration

The colon operator can also be used together with a for loop to iterate over a range of indices or elements in a list.

for item in my_list[2:]:
    print(item)
# 3
# 4
# 5

This code has iterated over the elements of my_list starting from index 2 and printed each element from that point onwards.

 

Video, Further Resources & Summary

Do you need more explanations on how to use a 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 tutorials on Statistics Globe:

This post has shown how to use the colon operator in a list in Python. In case you have further questions, don’t hesitate to let me know in the comments section below.

 

Paula Villasante Soriano Statistician & R Programmer

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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

The maximum upload file size: 2 MB. You can upload: image. Drop file here

Top