Back to series
· 13 min read

Python List Slicing and Sequence Operations


1. What Is List Slicing?

List slicing is a Python operation that extracts a portion of elements from a sequence. It can generate a new list based on a specified start position, end position, and step.

Slicing applies not only to lists but also to strings, tuples, byte sequences, and other sequence types that support slicing.

1. Basic Syntax

sequence[start:stop:step]

The meanings of the three parameters are:

Parameter Meaning Default behavior
start Starting index of the slice, inclusive Chosen based on the step direction
stop Ending index of the slice, exclusive Goes all the way to the sequence boundary
step Slice step Defaults to 1

For example:

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[1:4])
# [20, 30, 40]

print(numbers[:3])
# [10, 20, 30]

print(numbers[3:])
# [40, 50, 60]

print(numbers[:])
# [10, 20, 30, 40, 50, 60]

Slicing follows the left-closed, right-open principle:

numbers[start:stop]

This means it starts at start and ends before stop.

For example:

numbers = [10, 20, 30, 40, 50]

print(numbers[1:3])
# [20, 30]

The element at index 1 is included, while the element at index 3 is not included.

2. Differences Between Slicing and Indexing

Both indexing and slicing can access elements in a sequence, but their behavior differs.

numbers = [10, 20, 30, 40]

print(numbers[1])
# 20

print(numbers[1:3])
# [20, 30]

Main differences:

Comparison aspect Indexing Slicing
Access result A single element A sequence
Return type The element itself The slice type corresponding to the original sequence
Out-of-bounds behavior Usually raises IndexError Automatically truncates to the valid range
Step support No Yes
Creates a new object Not applicable Usually creates a new sequence object

For example:

numbers = [10, 20, 30]

# Index out of bounds
# print(numbers[10])
# IndexError

# Slicing out of bounds does not raise an error
print(numbers[1:100])
# [20, 30]

The fault tolerance of slicing makes it especially suitable for handling data of uncertain length.

2. Positive and Negative Indexing

Before understanding slicing, you need to grasp the indexing system of sequences.

1. Positive Indexing

Positive indexing goes from left to right, starting at 0.

numbers = [10, 20, 30, 40, 50]

# Index:   0   1   2   3   4
# Element: 10  20  30  40  50

print(numbers[0])
# 10

print(numbers[4])
# 50

2. Negative Indexing

Negative indexing goes from right to left, starting at -1.

numbers = [10, 20, 30, 40, 50]

# Index:   -5  -4  -3  -2  -1
# Element: 10  20  30  40  50

print(numbers[-1])
# 50

print(numbers[-2])
# 40

Negative indexing is suitable for locating elements from the end of a sequence.

3. Slicing with Negative Indexes

Positive and negative indexes can be mixed.

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[-4:-1])
# [30, 40, 50]

print(numbers[1:-1])
# [20, 30, 40, 50]

print(numbers[-3:])
# [40, 50, 60]

Note that the slice's ending position is still not included in the result.

4. Boundaries Between Index Positions and Elements

Slicing can be understood as selecting the elements between two boundaries.

numbers = [10, 20, 30, 40]

# Element:  10  20  30  40
# Boundary: 0   1   2   3   4

print(numbers[1:3])
# [20, 30]

There are two elements between boundary 1 and boundary 3.

This way of understanding can help analyze complex slices, especially negative indexing and step slicing.

III. Slice Step (step)

The step determines how many positions the slice moves each time.

1. Positive step

When the step is positive, elements are extracted from left to right.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[0:8:1])
# [0, 1, 2, 3, 4, 5, 6, 7]

print(numbers[0:8:2])
# [0, 2, 4, 6]

print(numbers[1:8:3])
# [1, 4, 7]

A step of 2 means moving forward two index positions each time.

2. Negative step

When the step is negative, elements are extracted from right to left.

numbers = [0, 1, 2, 3, 4, 5]

print(numbers[::-1])
# [5, 4, 3, 2, 1, 0]

print(numbers[5:1:-1])
# [5, 4, 3, 2]

print(numbers[4:0:-2])
# [4, 2]

With a negative step, the start position should usually be to the right of the end position.

3. Effect of Different Steps

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[::2])
# [0, 2, 4, 6, 8]

print(numbers[1::2])
# [1, 3, 5, 7, 9]

print(numbers[::-2])
# [9, 7, 5, 3, 1]

print(numbers[8:2:-2])
# [8, 6, 4]

The step determines not only the direction but also the interval between elements.

4. The Step Cannot Be Zero

The step of a slice cannot be 0.

numbers = [1, 2, 3, 4, 5]

# Raises ValueError
# print(numbers[::0])

Because a step of zero means the slice cannot move forward or backward.

IV. Common Slice Operations

Mastering common slice expressions can cover most list-slicing scenarios.

1. Get the First N Elements

numbers = [10, 20, 30, 40, 50]

print(numbers[:3])
# [10, 20, 30]

2. Get the Last N Elements

numbers = [10, 20, 30, 40, 50]

print(numbers[-2:])
# [40, 50]

3. Get the Middle Part

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[2:5])
# [30, 40, 50]

4. Get Elements Except the First and Last

numbers = [10, 20, 30, 40, 50]

print(numbers[1:-1])
# [20, 30, 40]

5. Reverse a List

numbers = [1, 2, 3, 4, 5]

reversed_numbers = numbers[::-1]

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

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

[::-1] creates a new list and does not modify the original list.

If you want to modify the original list directly, you can use:

numbers.reverse()

6. Get Every Other Element

numbers = [0, 1, 2, 3, 4, 5, 6, 7]

print(numbers[::2])
# [0, 2, 4, 6]

print(numbers[1::2])
# [1, 3, 5, 7]

7. Copy the Entire List

numbers = [10, 20, 30]

copied = numbers[:]

print(copied)
# [10, 20, 30]

print(copied is numbers)
# False

Using a full slice can create a new list object.

However, this is only a shallow copy; if the list contains nested mutable objects, the inner objects are still shared.

V. Slice Assignment: Modifying List Contents

List slices can not only read data but also modify the original list through assignment.

Unlike ordinary slicing, slice assignment acts directly on the original list.

1. Replace a Specified Range

numbers = [10, 20, 30, 40, 50]

numbers[1:3] = [200, 300]

print(numbers)
# [10, 200, 300, 40, 50]

The left side of the slice specifies the range to replace, and the right side provides the new iterable.

2. Replace a Different Number of Elements

Slice assignment allows the number of new elements to differ from the number of old elements.

numbers = [10, 20, 30, 40, 50]

numbers[1:3] = [200, 300, 400, 500]

print(numbers)
# [10, 200, 300, 400, 500, 40, 50]

Two elements were selected before, and now they are replaced with four, so the list becomes longer.

You can also reduce the number of elements:

numbers = [10, 20, 30, 40, 50]

numbers[1:4] = [200]

print(numbers)
# [10, 200, 50]

Slice assignment can change the length of a list.

3. Deleting elements with an empty list

Assigning an empty list to a slice is equivalent to deleting the corresponding range.

numbers = [10, 20, 30, 40, 50]

numbers[1:4] = []

print(numbers)
# [10, 50]

This is also a common way to delete with slices.

4. Inserting elements at a specified position using slices

When the slice range is empty, you can insert elements at the specified position.

numbers = [10, 20, 40, 50]

numbers[2:2] = [25, 30]

print(numbers)
# [10, 20, 25, 30, 40, 50]

numbers[2:2] represents an empty range, so it does not replace existing elements; instead, it inserts new elements at that position.

5. Augmented assignment: using +=

numbers = [1, 2, 3]

numbers += [4, 5]

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

The += operation on a list is usually implemented by extending it in place, rather than simply assigning the result to a brand-new list.

Compare this with ordinary addition:

numbers = [1, 2, 3]

result = numbers + [4, 5]

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

print(numbers)
# [1, 2, 3]

+ creates a new list, while += extends the list in place.

VI. Extended slice assignment

When a slice specifies a step, the assignment rules change.

1. Replacing with the same number of elements

numbers = [0, 1, 2, 3, 4, 5]

numbers[::2] = [10, 20, 30]

print(numbers)
# [10, 1, 20, 3, 30, 5]

The slice numbers[::2] selects three positions, so the right-hand side must also provide three elements.

2. Mismatched number of elements raises an error

numbers = [0, 1, 2, 3, 4, 5]

# Raises ValueError
# numbers[::2] = [10, 20]

Slice assignment with a step other than 1 requires the same number of elements on both sides.

3. Reverse replacement

numbers = [1, 2, 3, 4, 5]

numbers[::-1] = [10, 20, 30, 40, 50]

print(numbers)
# [50, 40, 30, 20, 10]

The first element on the right-hand side is written to the last position of the original list, and subsequent elements are written progressively toward the front.

VII. Slice deletion operations

Slices can also be used to delete one or more elements from a list.

1. Using del to delete a slice

numbers = [10, 20, 30, 40, 50]

del numbers[1:4]

print(numbers)
# [10, 50]

del does not return the deleted elements.

2. Deleting elements with a specified step

numbers = [0, 1, 2, 3, 4, 5, 6]

del numbers[::2]

print(numbers)
# [1, 3, 5]

This deletes the elements at indices 0、2、4、6.

3. Clearing the list

numbers = [1, 2, 3, 4, 5]

del numbers[:]

print(numbers)
# []

You can also use:

numbers.clear()

Both can clear the list, but del numbers[:] deletes all slice elements, while clear() is a dedicated clearing method.

Note that their behavior differs from rebinding the variable:

numbers = [1, 2, 3]
alias = numbers

numbers.clear()

print(numbers)
# []

print(alias)
# []

Clearing affects all variables that reference the same list object.

Whereas:

numbers = [1, 2, 3]
alias = numbers

numbers = []

print(numbers)
# []

print(alias)
# [1, 2, 3]

Here a new empty list is created and numbers is made to point to it, while the original list is not cleared.

VIII. Slice objects

Python provides the built-in slice type, which allows slice rules to be stored as an object for later reuse.

1. Creating a slice object

```python s = slice(1, 5, 2) numbers = [10, 20, 30, 40, 50, 60] print(numbers[s]) # [20, 40] ```

slice(start, stop, step) corresponds to the three parameters in the ordinary slicing syntax.

2. Inspecting slice parameters

```python s = slice(1, 8, 2) print(s.start) # 1 print(s.stop) # 8 print(s.step) # 2 ```

You can read the slice's start position, end position and step through its attributes.

3. Normalizing a slice with indices()

slice.indices(length) can convert a slice into a normalized start, stop and step based on the sequence length.

```python s = slice(None, None, -1) print(s.indices(5)) # (4, -1, -1) ```

This means that for a sequence of length 5, the reverse slice starts at index 4 and moves with a step of -1.

You can also do:

```python numbers = [10, 20, 30, 40, 50] s = slice(1, 100, 2) start, stop, step = s.indices(len(numbers)) print(start, stop, step) # 1 5 2 ```

The normalized boundaries will not exceed the range allowed by the given length.

4. Use cases for slice objects

When a program needs to dynamically extract data according to different conditions, slice objects can make the slicing logic clearer.

```python data = [ "A", "B", "C", "D", "E", "F", "G", "H" ] rules = { "first_half": slice(0, 4), "second_half": slice(4, 8), "every_second": slice(None, None, 2), "reverse": slice(None, None, -1) } for name, rule in rules.items(): print(name, data[rule]) ```

Output:

```text first_half ['A', 'B', 'C', 'D'] second_half ['E', 'F', 'G', 'H'] every_second ['A', 'C', 'E', 'G'] reverse ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'] ```

IX. Common Operations on Python Sequences

Lists are a sequence type. Beyond slicing, Python also provides many general operations that apply to sequences.

Common sequences include:

  • list: a list, a mutable sequence.
  • tuple: a tuple, an immutable sequence.
  • str: a string, an immutable sequence of text.
  • range: a sequence of integer ranges.
  • bytes: an immutable sequence of bytes.
  • bytearray: a mutable sequence of bytes.

1. Length: len()

```python numbers = [10, 20, 30, 40] print(len(numbers)) # 4 ```

len() returns the number of elements in the sequence.

2. Membership testing: in and not in

```python numbers = [10, 20, 30] print(20 in numbers) # True print(50 not in numbers) # True ```

Membership testing works for sequences such as lists, tuples and strings.

For lists, membership testing usually requires a linear scan, giving a time complexity of O(n).

3. Sequence concatenation: +

```python a = [1, 2, 3] b = [4, 5, 6] result = a + b print(result) # [1, 2, 3, 4, 5, 6] ```

+ creates a new list and does not modify the original lists.

The two objects being concatenated generally need to be of the same sequence type:

```python # Concatenating different sequence types directly is not supported # [1, 2] + (3, 4) # TypeError ```

4. Sequence repetition: *

```python numbers = [1, 2, 3] print(numbers * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3] ```

A repetition operation creates a new sequence.

Note in particular that when a nested mutable object inside a list is repeated, the inner object is not copied:

```python matrix = [[0] * 2] * 3 matrix[0][0] = 100 print(matrix) # [[100, 0], [100, 0], [100, 0]] ```

All three positions reference the same inner list.

To correctly create independent two-dimensional lists:

matrix = [[0] * 2 for _ in range(3)]

matrix[0][0] = 100

print(matrix)
# [[100, 0], [0, 0], [0, 0]]

5. Minimum and Maximum Values

numbers = [10, 30, 20, 50, 40]

print(min(numbers))
# 10

print(max(numbers))
# 50

min() and max() can find the minimum and maximum values among comparable elements.

For custom objects, you can specify the comparison basis with key:

students = [
    {"name": "Alice", "score": 90},
    {"name": "Bob", "score": 85},
    {"name": "Cindy", "score": 95}
]

best = max(students, key=lambda item: item["score"])

print(best)
# {'name': 'Cindy', 'score': 95}

6. Summing: sum()

numbers = [10, 20, 30, 40]

print(sum(numbers))
# 100

sum() is mainly used for numeric data that can be added together.

7. Finding an Index: index()

numbers = [10, 20, 30, 20]

print(numbers.index(20))
# 1

index() returns the index of the first matching element.

You can specify the search range:

numbers = [10, 20, 30, 20, 40]

print(numbers.index(20, 2))
# 3

If the element is not found, a ValueError is raised.

8. Counting Occurrences: count()

numbers = [10, 20, 20, 30, 20]

print(numbers.count(20))
# 3

count() returns the number of times the specified element appears in the sequence.

9. Comparing Sequences

Lists can be compared for equality and can also be compared lexicographically for order.

a = [1, 2, 3]
b = [1, 2, 3]
c = [1, 2, 4]

print(a == b)
# True

print(a < c)
# True

Sequence comparison usually compares elements one by one from left to right:

  1. Find the first element that is not equal.
  2. Determine the overall result based on the comparison result of that element.
  3. If all corresponding elements are equal, the shorter sequence is usually less than the longer sequence.

For example:

print([1, 2, 3] < [1, 2, 4])
# True

print([1, 2] < [1, 2, 3])
# True

print([2] < [1, 9])
# False

The corresponding elements involved in an ordering comparison must be able to be compared accordingly; otherwise, a TypeError may be raised.

10. Differences in Slicing Lists, Tuples, and Strings

Slicing is a capability shared by sequences, but different sequence types return different results and have different modification capabilities.

1. List Slicing

numbers = [10, 20, 30, 40]

result = numbers[1:3]

print(result)
# [20, 30]

result[0] = 200

print(result)
# [200, 30]

print(numbers)
# [10, 20, 30, 40]

List slicing creates a new list.

2. Tuple Slicing

numbers = (10, 20, 30, 40)

result = numbers[1:3]

print(result)
# (20, 30)

Tuple slicing returns a tuple, and you cannot modify elements via slice assignment.

3. String Slicing

text = "Python"

print(text[0:3])
# Pyt

print(text[::-1])
# nohtyP

String slicing returns a new string. Strings themselves are immutable, so you cannot use slice assignment to modify characters.

4. Byte Sequence Slicing

data = bytes([65, 66, 67, 68])

print(data[1:3])
# b'BC'

print(data[::-1])
# b'DCBA'

Slicing a bytes object returns a new bytes object.

For bytearray:

data = bytearray([65, 66, 67, 68])

data[1:3] = bytearray([88, 89])

print(data)
# bytearray(b'AXYD')

bytearray is a mutable byte sequence, so it supports slice assignment.

XI. Two-Dimensional Lists and Nested List Slicing

A two-dimensional list is essentially a list made up of multiple lists, so it supports multi-level indexing and slicing.

1. Accessing Elements of a Two-Dimensional List

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[1][2])
# 6

First access the outer list, then access the inner list.

2. Getting a Specified Row

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[1])
# [4, 5, 6]

3. Getting Multiple Rows

print(matrix[0:2])
# [[1, 2, 3], [4, 5, 6]]

What is returned here is a new outer list, but each row within it still references the original inner list.

rows = matrix[0:2]

rows[0][0] = 100

print(matrix[0])
# [100, 2, 3]

This shows that slicing a two-dimensional list still follows the shallow copy rule.

4. Getting a Specified Column

Ordinary Python lists do not have multi-dimensional slicing syntax like NumPy does.

You need to extract the specified column using a comprehension:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

second_column = [row[1] for row in matrix]

print(second_column)
# [2, 5, 8]

5. Getting a Submatrix

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

sub_matrix = [
    row[1:3]
    for row in matrix[0:2]
]

print(sub_matrix)
# [[2, 3], [6, 7]]

This approach can extract a local region from a two-dimensional list.

6. Multi-Dimensional Arrays and NumPy Slicing

When the data is large in scale, or when scientific computing is required, you can use NumPy.

import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

print(matrix[0:2, 1:3])
# [[2 3]
#  [5 6]]

NumPy supports multi-dimensional slicing, allowing you to specify row and column ranges at the same time.

Unlike ordinary Python lists, basic NumPy slicing usually returns a view of the original array, and modifying the view may affect the original array.

import numpy as np

matrix = np.array([
    [1, 2],
    [3, 4]
])

view = matrix[:1, :]

view[0, 0] = 100

print(matrix)
# [[100   2]
#  [  3   4]]

If you need independent data, you can make an explicit copy:

copied = matrix[:1, :].copy()

XII. Shallow Copy and Deep Copy in Slicing

Slicing creates a new outer list, but it does not recursively copy the nested objects within it.

This is a very important point for understanding Python list slicing.

1. Slicing an Ordinary List

numbers = [1, 2, 3]

copied = numbers[:]

print(copied is numbers)
# False

The two list objects are different.

2. Slicing a Nested List

data = [
    [1, 2],
    [3, 4]
]

copied = data[:]

print(copied is data)
# False

print(copied[0] is data[0])
# True

The outer list is copied, but the inner lists are still shared.

3. The Impact of Shallow Copy

data = [
    [1, 2],
    [3, 4]
]

copied = data[:]

copied[0][0] = 100

print(data)
# [[100, 2], [3, 4]]

Because the first element in both outer lists references the same inner list, changes to one affect the other.

4. Using copy.deepcopy()

If you need to recursively copy nested objects, you can use copy.deepcopy().

import copy

data = [
    [1, 2],
    [3, 4]
]

copied = copy.deepcopy(data)

copied[0][0] = 100

print(data)
# [[1, 2], [3, 4]]

print(copied)
# [[100, 2], [3, 4]]

Note that deep copy processes objects according to their types and the copy protocol; it does not mean that all external resources can truly be copied.

5. Comparison of Different Copy Methods

Method Creates a new outer list Recursively copies nested objects
numbers[:] Yes No
numbers.copy() Yes No
list(numbers) Yes No
copy.copy(numbers) Yes No
copy.deepcopy(numbers) Yes Yes, handled according to the deep copy protocol

13. Performance and Time Complexity of Slicing

Although slice expressions are concise, they still involve object creation and copying of element references.

Understanding their complexity helps when working with large-scale data.

1. Ordinary List Slicing

numbers = list(range(1000000))

part = numbers[100:10000]

Slicing requires creating a new list and placing references to the selected elements into the new list.

Let the slice result contain k elements:

  • Time complexity: O(k)
  • Space complexity: O(k)

The space complexity here mainly refers to the space required by the new list to store element references, excluding the referenced objects themselves.

2. Full Slicing

copied = numbers[:]

A full slice copies all element references.

For a list containing n elements:

  • Time complexity: O(n)
  • Space complexity: O(n)

Therefore, frequently performing full slices on large lists incurs additional memory overhead.

3. Single-Element Indexing

value = numbers[100]

Python lists are typically implemented as dynamic arrays, so accessing by index has a time complexity of O(1).

This is a typical characteristic of common implementations such as CPython, not an underlying structure that all Python implementations must use.

4. Slice Assignment

numbers[100:200] = [0] * 100

Slice assignment involves replacing elements, shifting subsequent elements, and possible capacity adjustments.

Its complexity depends on the following factors:

  • The number of elements being replaced.
  • The number of new elements.
  • The insertion or deletion position.
  • The number of subsequent elements that need to be moved.
  • Whether the list's underlying capacity needs to be adjusted.

Therefore, it cannot simply be assumed that all slice assignments are O(k).

5. Complexity of Common Operations

The following are typical complexities based on common dynamic array implementations: