How to Slice Lists in Python?

In this tutorial, I will explain how to slice lists in Python. As a developer working on a project, I came across a scenario where I needed to slice lists in Python. After researching and testing with various methods, I found a few important methods to accomplish this task. I will share my findings with examples.

Slice Lists in Python

In Python, list slicing is a way to extract a portion of a list by specifying a range of indices. It allows you to retrieve a new list containing elements from the original list based on the specified range. The syntax for list slicing is as follows:

my_list[start:end:step]
  • start: The starting index of the slice (inclusive). If omitted, it defaults to the beginning of the list.
  • end: The ending index of the slice (exclusive). If omitted, it defaults to the end of the list.
  • step: The step value or stride, specifying the increment between each element in the slice. If omitted, it defaults to 1.

Read How to Concatenate a List of Strings into a Single String in Python?

Basic List Slicing

Let’s say we have a list of cities in the USA:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Philadelphia", "Phoenix", "San Antonio", "San Diego", "Dallas", "San Jose"]

To slice this list and obtain a subset of cities, we can use the following syntax:

subset = cities[start:end]

For example, to get the first three cities, we can do:

first_three = cities[0:3]
print(first_three)  # Output: ['New York', 'Los Angeles', 'Chicago']

Notice that the slice includes the element at index 0 (inclusive) and goes up to, but does not include, the element at index 3 (exclusive).

We can also omit the start or end index:

first_five = cities[:5]
print(first_five)  

last_three = cities[-3:]
print(last_three) 

Output:

['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia']
['San Diego', 'Dallas', 'San Jose']

You can see the output in the screenshot below.

Slice Lists in Python

Check out How to Iterate Through a List Backward in Python?

Slicing with Step

In addition to specifying the start and end indices, we can also include a step value to skip elements in the slice. The step value determines the increment between each element in the resulting slice in Python.

every_other_city = cities[::2]
print(every_other_city)

Output:

['New York', 'Chicago', 'Philadelphia', 'San Antonio', 'Dallas']

You can see the output in the screenshot below.

How to Slice Lists in Python

In this example, we start from the beginning of the list (default start index) and go until the end of the list (default end index), but we skip every other element by using a step value of 2.

We can also use negative step values to slice the list in reverse order:

reversed_cities = cities[::-1]
print(reversed_cities) 

Output:

['San Jose', 'Dallas', 'San Diego', 'San Antonio', 'Phoenix', 'Philadelphia', 'Houston', 'Chicago', 'Los Angeles', 'New York']

You can see the output in the screenshot below.

Slice Lists in Python with variables

Read How to Clear a List in Python?

Slicing with Variables

Instead of hardcoding the start and end indices, we can use variables to make our code more flexible and reusable in Python. This is particularly useful when the indices are computed dynamically or based on user input.

start_index = 2
end_index = 7
selected_cities = cities[start_index:end_index]
print(selected_cities)  
# Output: ['Chicago', 'Houston', 'Philadelphia', 'Phoenix', 'San Antonio']

Check out How to Check if an Element is Not in a List in Python?

Modifying Lists with Slicing

List slicing not only allows us to extract elements but also to modify specific portions of a Python list. We can assign new values to a slice of a list to replace the existing elements.

cities[3:6] = ["Austin", "Jacksonville", "Fort Worth"]
print(cities)  
# Output: ['New York', 'Los Angeles', 'Chicago', 'Austin', 'Jacksonville', 'Fort Worth', 'San Antonio', 'San Diego', 'Dallas', 'San Jose']

In this example, we replace the cities at indices 3, 4, and 5 with new cities using list slicing and assignment.

Read How to Add Elements to an Empty List in Python?

Example

Let’s consider a real-world scenario where Python list slicing can be useful. Suppose you have a list of sales data for different regions in the USA:

sales_data = [10000, 15000, 20000, 12000, 18000, 25000, 22000, 30000, 28000, 35000]

You want to analyze the sales data for a specific quarter (e.g., Q2) which corresponds to indices 3, 4, and 5 in the list. You can use list slicing to extract the relevant data:

q2_sales = sales_data[3:6]
print(q2_sales)  
# Output: [12000, 18000, 25000]

Now you have a new list (q2_sales) containing only the sales data for the second quarter, making it easier to perform further analysis or calculations.

Check out How to Remove None Values from a List in Python?

Conclusion

In this tutorial, I explained how to slice lists in Python. I discussed basic slicing, slicing with steps, slicing with variables, and modifying lists with slicing. I also covered a real-world example, which will help you to understand better.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.