Slicing and unpacking¶
In this tutorial, you will learn advanced techniques for extracting and selecting data from sequences using slicing and unpacking.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Completed tutorials 01 through 05 (lists, tuples, dictionaries, sets, and comprehensions)
Learning objectives¶
By the end of this tutorial, you will be able to:
- Use slicing with a step value to select items at intervals
- Reverse sequences using slicing
- Assign to slices to replace parts of a list
- Use extended unpacking with the
*operator - Apply practical patterns combining slicing and unpacking
Review of basic slicing¶
You learned the basics of slicing in Working with lists. The syntax sequence[start:stop] extracts items from start up to (but not including) stop:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # Items at index 2, 3, 4
print(numbers[:4]) # First four items
print(numbers[6:]) # Everything from index 6 onwards
Slicing with a step¶
The full slicing syntax is sequence[start:stop:step]. The step value controls how many items to skip between selections:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[::2]) # Every second item
print(numbers[1::2]) # Every second item, starting from index 1
print(numbers[::3]) # Every third item
Reversing sequences¶
A step of -1 reverses the sequence:
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])
word = "Python"
print(word[::-1])
Slicing strings¶
Slicing works the same way on strings as it does on lists and tuples:
message = "Hello, World!"
print(message[:5]) # "Hello"
print(message[7:]) # "World!"
print(message[::2]) # Every second character
Assigning to slices¶
With lists (but not tuples or strings, which are immutable), you can assign to a slice to replace part of the list:
colours = ["red", "green", "blue", "yellow", "purple"]
# Replace items at index 1 and 2
colours[1:3] = ["lime", "cyan"]
print(colours)
The replacement does not need to be the same length as the slice:
letters = ["a", "b", "c", "d", "e"]
# Replace two items with three
letters[1:3] = ["x", "y", "z"]
print(letters)
Basic unpacking¶
Unpacking assigns each item in a sequence to a separate variable:
coordinates = [51.5074, -0.1278, 11.0]
latitude, longitude, elevation = coordinates
print(f"Latitude: {latitude}")
print(f"Longitude: {longitude}")
print(f"Elevation: {elevation} metres")
Extended unpacking with *¶
The * operator collects remaining items into a list. This is particularly useful when you want the first or last items separately:
scores = [95, 87, 92, 78, 88, 91]
first, *middle, last = scores
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")
head, *tail = [1, 2, 3, 4, 5]
print(f"Head: {head}")
print(f"Tail: {tail}")
Unpacking in function calls¶
You can use * to unpack a list into function arguments and ** to unpack a dictionary into keyword arguments:
def greet(first_name, last_name, city):
print(f"Hello, {first_name} {last_name} from {city}!")
# Unpack a list into positional arguments
details = ["Alice", "Smith", "London"]
greet(*details)
# Unpack a dictionary into keyword arguments
info = {"first_name": "Bob", "last_name": "Jones", "city": "Manchester"}
greet(**info)
Swapping variables¶
Unpacking provides an elegant way to swap variable values without a temporary variable:
a = "first"
b = "second"
a, b = b, a
print(f"a = {a}")
print(f"b = {b}")
data = list(range(1, 11))
chunk_size = 3
chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
print(chunks)
Getting the first and last items¶
items = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
first, *_, last = items
print(f"First: {first}, Last: {last}")
The underscore _ is a convention for values you do not need.
Exercise: weekly temperatures¶
You have a list of daily temperatures (in degrees Celsius) for a week, from Monday to Sunday:
temperatures = [12.5, 14.0, 13.5, 15.0, 16.5, 18.0, 17.5]
Using slicing and unpacking:
- Use slicing to get the weekday temperatures (Monday to Friday) and weekend temperatures (Saturday and Sunday)
- Use unpacking to assign the first day and last day temperatures to separate variables
- Find the highest and lowest temperatures across the whole week
# Write your code here
Solution¶
Here is one way to complete the exercise:
temperatures = [12.5, 14.0, 13.5, 15.0, 16.5, 18.0, 17.5]
# 1. Weekday and weekend temperatures
weekdays = temperatures[:5]
weekend = temperatures[5:]
print(f"Weekdays: {weekdays}")
print(f"Weekend: {weekend}")
# 2. First and last day
monday, *_, sunday = temperatures
print(f"Monday: {monday}°C")
print(f"Sunday: {sunday}°C")
# 3. Highest and lowest
print(f"Highest: {max(temperatures)}°C")
print(f"Lowest: {min(temperatures)}°C")
Summary¶
In this tutorial, you learned how to:
- Use slicing with a step value
[start:stop:step] - Reverse sequences with
[::-1] - Slice strings in the same way as lists
- Assign to slices to replace parts of a list
- Use extended unpacking with
*to capture remaining items - Unpack sequences into function arguments with
*and** - Swap variables elegantly with unpacking
Congratulations¶
You have completed all six tutorials in the Data Structures with Python series. You now have a solid foundation in lists, tuples, dictionaries, sets, comprehensions, slicing, and unpacking.
To continue learning: