Python Slicing Syntax: Master List Extraction with [start:stop:step]

Python lists are a powerful data type for storing ordered data. While you can access a single element using [0], Python also allows you to extract a range of elements to create a new list, such as “from the 1st to the 3rd element.”

This feature is called Slicing. It is an essential operation for data processing, analysis, and web development.

This article explains the [start:stop:step] slicing syntax from basic usage to advanced applications.


目次

Basic Slicing Syntax [start:stop:step]

To slice a list, place [] immediately after the variable name and specify the range using colons (:).

Syntax: my_list[start:stop:step]

  • start: The index where the slice begins. This element is included.
  • stop: The index where the slice ends. This element is excluded (the slice goes up to, but does not include, this index).
  • step: The interval (stride) between elements.

Let’s look at the most basic form [start:stop], where step is omitted.


1. Basic Slicing [start:stop]

When step is omitted, it defaults to 1 (include every element in the range). We will use a list of weekdays for this example.

weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# Index:      0      1      2      3      4      5      6

Specifying both start and stop The key point is that start is inclusive, but stop is exclusive.

# From index 1 ("Tue") up to index 4 ("Fri")
# This extracts [1] "Tue", [2] "Wed", [3] "Thu"
mid_days = weekdays[1:4]

print(f"weekdays[1:4] -> {mid_days}")

Output:

weekdays[1:4] -> ['Tue', 'Wed', 'Thu']

2. Omitting start or stop

In slicing syntax, start and stop can be omitted.

  • Omitting start ([:stop]): From the beginning (index 0) up to stop.
  • Omitting stop ([start:]): From start to the end of the list.
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

# 1. From the beginning up to index 3 ("Thu")
# Includes [0], [1], [2]
first_three = weekdays[:3]
print(f"weekdays[:3] -> {first_three}")

# 2. From index 4 ("Fri") to the end
# Includes [4], [5], [6]
last_three = weekdays[4:]
print(f"weekdays[4:] -> {last_three}")

# 3. Omitting both ([:] )
# This is a common idiom to create a copy of the entire list
all_days_copy = weekdays[:]
print(f"weekdays[:] -> {all_days_copy}")

Output:

weekdays[:3] -> ['Mon', 'Tue', 'Wed']
weekdays[4:] -> ['Fri', 'Sat', 'Sun']
weekdays[:] -> ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

3. Slicing with step

By specifying step, you can skip elements.

  • step is 2: Get every other element.
  • step is -1: Reverse the list.
numbers = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

# [start:stop:step]
# From start to end, taking every 2nd element (step=2)
even_tens = numbers[::2]
print(f"numbers[::2] -> {even_tens}")

# From index 1 to end, taking every 2nd element
odd_tens = numbers[1::2]
print(f"numbers[1::2] -> {odd_tens}")

# Reverse the entire list (step=-1)
reversed_nums = numbers[::-1]
print(f"numbers[::-1] -> {reversed_nums}")

Output:

numbers[::2] -> [0, 20, 40, 60, 80]
numbers[1::2] -> [10, 30, 50, 70, 90]
numbers[::-1] -> [90, 80, 70, 60, 50, 40, 30, 20, 10, 0]

4. Negative Indices and Slicing

You can also use negative indices, which count from the end of the list.

  • [-1] is the last element.
  • [-2] is the second to last element.

Using a negative index for stop allows you to easily “exclude N items from the end.”

weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

# 1. From the beginning up to the second to last element (-2)
# Basically [0] to [4]
except_last_two = weekdays[:-2]
print(f"weekdays[:-2] -> {except_last_two}")

# 2. From index 1 up to the last element (-1)
# Trims the first and last elements
center_part = weekdays[1:-1]
print(f"weekdays[1:-1] -> {center_part}")

Output:

weekdays[:-2] -> ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
weekdays[1:-1] -> ['Tue', 'Wed', 'Thu', 'Fri', 'Sat']

Summary

  • The basic syntax is [start:stop:step].
  • start is inclusive, and stop is exclusive.
  • Omitting start starts from the beginning; omitting stop goes to the end.
  • Specifying step allows skipping elements. [::-1] is a standard idiom for reversing a list.
  • Slicing always creates and returns a new list; it does not modify the original list.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次