5.9 List Slicing (BT101CO)

List Slicing is a powerful feature in Python that allows you to extract a specific portion (a "slice") of a list to create a new list. While indexing retrieves a single item, slicing retrieves a sub-sequence.

1. The Three Parameters

The standard syntax for slicing is: list_name[start : stop : step]

  • start: The index where the slice begins (inclusive). If omitted, it defaults to 0.
  • stop: The index where the slice ends (exclusive). The element at this index is not included. If omitted, it defaults to the end of the list.
  • step: The increment between each index (optional). If omitted, it defaults to 1.

2. Basic Slicing Examples

Assume we have the following list: letters = ['A', 'B', 'C', 'D', 'E', 'F']

Slice Code Result Explanation
letters[1:4]['B', 'C', 'D']From index 1 to 3 (stops before 4).
letters[:3]['A', 'B', 'C']From the beginning to index 2.
letters[2:]['C', 'D', 'E', 'F']From index 2 to the very end.
letters[:]['A', 'B', 'C', 'D', 'E', 'F']Creates a full copy of the list.

3. Slicing with a step

The step value determines how many items to skip.

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

# Get every second element
print(numbers[::2])   # Output: [0, 2, 4, 6, 8]

# Get elements from index 1 to 7, skipping every other one
print(numbers[1:8:2]) # Output: [1, 3, 5, 7]

4. Negative Slicing and Reversing

You can use negative numbers for any of the three parameters. This is particularly useful for working from the end of the list or reversing data.

  • Last three items: letters[-3:]['D', 'E', 'F']
  • Reverse the entire list: letters[::-1]['F', 'E', 'D', 'C', 'B', 'A']
  • Everything except the last two: letters[:-2]['A', 'B', 'C', 'D']

5. Modifying Lists via Slicing

Because lists are mutable, you can actually use slicing on the left side of the assignment operator to replace multiple elements at once.

colors = ["red", "green", "blue", "yellow"]
colors[1:3] = ["pink", "black"]
print(colors) # Output: ['red', 'pink', 'black', 'yellow']

Summary Checklist for Slicing

Goal Shortcut
First n elementslist[:n]
Last n elementslist[-n:]
Skip every n-th itemlist[::n]
Reverse the listlist[::-1]

Slicing is a core skill for data manipulation, allowing for concise and readable code.

Practice Quiz