How to unpack a list in Python

Learn how to unpack lists in Python. This guide covers various methods, tips, real-world examples, and common errors to help you master it.

How to unpack a list in Python
Published on: 
Tue
Feb 24, 2026
Updated on: 
Mon
Apr 6, 2026
The Replit Team

Unpacking a list in Python lets you assign its items to variables in a single statement. It's a powerful technique that streamlines your code, improves readability, and helps manage data efficiently.

In this article, you'll explore several unpacking methods, including the * operator for flexible assignments. You'll also get practical tips, see real-world applications, and learn to debug common errors.

Basic unpacking to multiple variables

numbers = [1, 2, 3]
a, b, c = numbers
print(f"a: {a}, b: {b}, c: {c}")--OUTPUT--a: 1, b: 2, c: 3

The line a, b, c = numbers is where the unpacking happens. It assigns each item from the numbers list to a variable on the left, in order—a becomes 1, b becomes 2, and c becomes 3.

For this to work, the number of variables must exactly match the number of items in the list. If they don't, Python raises a ValueError. It's a much cleaner alternative to manually indexing each element, which improves your code's readability.

Essential unpacking techniques

Building on basic unpacking, you can handle more complex situations with flexible tools like the * operator, unpacking in for loops, and ignoring values with _.

Unpacking with the * operator

first, *middle, last = [1, 2, 3, 4, 5]
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")--OUTPUT--First: 1
Middle: [2, 3, 4]
Last: 5

The * operator adds powerful flexibility, allowing one variable to capture multiple items from a list. This is especially useful when you don't know the exact length of the sequence you're unpacking. It solves the "too many values to unpack" error by assigning leftover items to a memory-efficient new list.

In the expression first, *middle, last:

  • The first variable is assigned the first item, 1.
  • The last variable gets the final item, 5.
  • The starred variable, *middle, collects all elements in between into a new list: [2, 3, 4].

Unpacking in a for loop

pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
for number, letter in pairs:
   print(f"Number: {number}, Letter: {letter}")--OUTPUT--Number: 1, Letter: a
Number: 2, Letter: b
Number: 3, Letter: c

Unpacking works seamlessly inside for loops, making it easy to process lists of tuples or other structured sequences. Instead of handling each tuple as a single item, you can break it down into its components on the fly.

  • In each iteration over the pairs list, Python assigns the first element of the tuple to number and the second to letter.

This is far more readable than manually accessing elements with index positions like pair[0] and pair[1], as it clearly states what each variable represents. This focus on readability aligns with vibe coding principles of writing natural, intuitive code.

Ignoring unwanted values with _

data = [(1, 'apple', 'red'), (2, 'banana', 'yellow')]
for id, fruit, _ in data:
   print(f"ID: {id}, Fruit: {fruit}")--OUTPUT--ID: 1, Fruit: apple
ID: 2, Fruit: banana

You can use an underscore _ as a placeholder for values you want to discard. It's a common Python convention that signals a variable is intentionally unused, which helps keep your code clean and readable.

  • In the loop for id, fruit, _ in data:, the third item in each tuple (the color) is assigned to _ and effectively ignored.
  • This lets you focus only on the data you need—in this case, the id and fruit.

Advanced unpacking techniques

With the basics covered, you can apply unpacking to more complex scenarios like passing arguments with *args, swapping variables, and handling multiple iterables using zip().

Using *args to unpack lists into function arguments

def sum_values(x, y, z):
   return x + y + z

values = [1, 2, 3]
result = sum_values(*values)
print(f"Sum: {result}")--OUTPUT--Sum: 6

You can use the * operator to unpack a list's items directly into a function's arguments. This is handy when your data is in a list, but the function you're calling expects separate positional arguments.

  • In the call sum_values(*values), the asterisk tells Python to pass each item from the values list as an individual argument.
  • It's effectively the same as calling the function like this: sum_values(1, 2, 3).

This technique makes your code more flexible, allowing you to adapt data structures to fit different function signatures without manual indexing.

Swapping values with unpacking

a, b = 10, 20
a, b = b, a
print(f"a: {a}, b: {b}")--OUTPUT--a: 20, b: 10

Unpacking provides a concise, one-line solution for swapping variable values—a common task that traditionally requires a temporary variable. It’s a classic example of Python’s focus on code readability.

  • The expression a, b = b, a works by first evaluating the right side, which creates a temporary tuple from the current values of b and a.
  • Next, Python unpacks that tuple, assigning its items back to the variables on the left in their new order.

Unpacking multiple iterables with zip()

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
   print(f"{name} is {age} years old")--OUTPUT--Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

The zip() function is perfect for processing multiple lists in parallel. It pairs corresponding elements from each iterable—in this case, names and ages—into a sequence of tuples.

  • The for loop then iterates over these tuples, and the expression for name, age in zip(...) unpacks each one.

This lets you work with related data from different sources in a clean, synchronized way. The process automatically stops as soon as the shortest list runs out of items.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This environment lets you immediately apply what you've learned about list unpacking in a real project.

To build even faster, Agent 4 can turn your ideas into complete applications. Instead of piecing together techniques, you describe the tool you need, and the Agent builds it. For example, you could ask it to create:

  • A log parser that unpacks structured log entries, like (timestamp, level, message), to filter and display only critical errors.
  • A command-line tool that separates the first argument as a command and gathers the rest into a list of options using the * operator.
  • A data mapping utility that combines user IDs from one list with their corresponding emails from another using zip() to create a unified contact list.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Knowing how to fix common unpacking errors, like ValueError and TypeError, will make your code more robust and reliable. This skill in debugging common errors is essential for any Python developer.

Fixing ValueError when unpacking with mismatched lengths

A ValueError is the most common unpacking error. It occurs when the number of variables doesn't match the number of items in the list. Python raises this error because it can't resolve the mismatch, as shown in the following code.

numbers = [1, 2, 3, 4]
a, b, c = numbers  # Too few variables for the values
print(f"a: {a}, b: {b}, c: {c}")

The numbers list contains four items, but you're only providing three variables—a, b, and c—to hold them. Python can't complete the assignment, so it raises an error. The code below shows how to fix this.

numbers = [1, 2, 3, 4]
a, b, c, d = numbers  # Matching number of variables
print(f"a: {a}, b: {b}, c: {c}, d: {d}")

The fix is simple: ensure the number of variables matches the number of list items. By changing the assignment to a, b, c, d = numbers, you provide one variable for each of the four values, resolving the ValueError. This error often pops up when dealing with data of unpredictable length, such as parsing file lines or handling API responses, so always double-check your variable count against the expected data structure.

Handling empty sequences when unpacking with the * operator

The * operator avoids a ValueError with short sequences by assigning an empty list to the starred variable. While not an error, this can cause bugs if your code expects values. The following code shows what happens when there are no items left.

first, *middle, last = [1, 2]
print(f"First: {first}, Middle: {middle}, Last: {last}")

Because the list only has two items, first gets 1 and last gets 2. This leaves *middle with no values, so it becomes an empty list. See the result in the output below.

first, *middle, last = [1, 2, 3, 4]
print(f"First: {first}, Middle: {middle}, Last: {last}")

When a list has enough items, the * operator gathers all the elements between the first and last into a new list. For example, in first, *middle, last = [1, 2, 3, 4], the *middle variable becomes [2, 3]. This flexible assignment is ideal for handling data of varying lengths, like command-line arguments or log entries, where you need to separate the core data from the start and end markers.

Resolving TypeError when unpacking non-iterables

A TypeError occurs when you attempt to unpack a value that isn't iterable, such as an integer. Unpacking is designed for sequences like lists and tuples, not single data types. The following code triggers this error by trying to unpack an integer.

number = 12345
a, b, c = number  # TypeError: 'int' object is not iterable
print(f"a: {a}, b: {b}, c: {c}")

The assignment a, b, c = number fails because the integer 12345 is a single unit, not a sequence of individual digits to distribute. Check the code below for the correct way to handle this.

number = 12345
a, b, c = str(number)[:3]  # Convert to string and take first 3 chars
print(f"a: {a}, b: {b}, c: {c}")

To resolve the TypeError, you must convert the non-iterable value into a sequence. The solution a, b, c = str(number)[:3] works by first turning the integer into a string with str(). Since strings are iterable, Python can then unpack the first three characters from the sliced string into the variables a, b, and c. Keep an eye out for this error when a function returns a single value instead of an expected list.

Real-world applications

Beyond fixing errors, unpacking is invaluable for managing complex data, like iterating through dictionary key-value pairs with .items() or navigating nested structures.

Unpacking dictionary items with .items()

The .items() method is the key to unpacking dictionaries, letting you loop through key-value pairs and assign them to separate variables simultaneously.

user_data = {'username': 'john_doe', 'email': 'john@example.com', 'age': 30}
for key, value in user_data.items():
   print(f"{key}: {value}")

The .items() method effectively converts each entry in the user_data dictionary into a (key, value) tuple. The for loop then iterates over this sequence of tuples.

  • In each iteration, Python unpacks the tuple, assigning the first item to key and the second to value.
  • This gives you direct access to both pieces of data, which is more efficient and readable than looking up the value with user_data[key] inside the loop.

Nested unpacking for complex data structures

You can even unpack nested data structures, extracting values from a sequence within a sequence by mirroring its structure in your variable assignment.

people = [('Alice', 25, ('New York', 'USA')),
         ('Bob', 30, ('London', 'UK'))]

for name, age, (city, country) in people:
   print(f"{name} is {age} years old and lives in {city}, {country}")

This code demonstrates how Python handles nested data during unpacking. The for loop iterates through the people list, where each item is a tuple that contains another tuple.

  • The expression name, age, (city, country) unpacks both the outer and inner tuples in a single, readable statement.
  • name and age are assigned the first two values from the outer tuple.
  • The parentheses in (city, country) instruct Python to unpack the third element—the location tuple—into the city and country variables.

It’s a clean way to access deeply nested information without extra steps.

Get started with Replit

Now, turn your knowledge into a tool with Replit Agent. Describe what you want: “a CLI that separates a command from *args” or “a script to zip() user IDs with profile data.”

The Agent writes the code, tests for errors, and deploys your application for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.