List Unpacking
The last thing we need to learn about lists is List Unpacking.
Imagine we have a list: nums = [0, 1, 2, 3]. We can "unpack" that list by assigning it to comma-separated variables in one go:
- Print a, what do you see?
- Now try b, c and d.
The Asterisk (*) Catch-All
Check this out: if you have a long list but only a few variables, you can use the * operator to capture the "rest."
- Print other.
-
You can even sandwich the asterisk. If you try:
a, b, c, *other, d, e = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - Print other.
The Takeaway
You might be thinking: "When will I ever need to use this in my programming life?" Like many things in coding, you don't need to memorize every detail. You just need to understand the concept. When you're faced with a problem in the future, you'll recall that a solution exists and you can look up the syntax. Knowing that List Unpacking is a tool in your kit is enough for now.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named list_unpacking.py in your part26 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: The Podium Finish
The race results are in, and we need to separate the medalists from the rest of the pack.
-
Starting List:
runners = ['Swift', 'Bolt', 'Flash', 'Shadow', 'Turbo'] -
Task: Use unpacking to assign the first runner to
gold, the second tosilver, and the remaining runners to a list calledthe_pack. -
Goal: Print
gold,silver, andthe_pack.
Exercise 2: Sensor Stripping
We received a data packet where the first item is a date, the last is a location, and everything in between is a temperature reading.
-
Starting List:
data = ['2026-02-17', 22.5, 23.1, 21.8, 'Station_A'] -
Task: Use a single line of unpacking to capture the
date, thelocation, and a list oftemps. - Goal: Print the
tempslist.
Exercise 3: Professional Ignoring
We only need the username from a profile list, and we want to ignore the sensitive data that follows.
-
Starting List:
user = ['admin', 'P@ssword!', '192.168.1.1', 'SuperUser'] -
Task: Unpack the first item into
usernameand use*_to ignore everything else. -
Goal: Print
usernameand verify no other specific variables were created.
Don't Forget to commit and Push!