Loading episodes…
0:00 0:00

Mastering Python Unpacking: From Basics to Advanced Tricks

00:00
BACK TO HOME

Mastering Python Unpacking: From Basics to Advanced Tricks

10xTeam January 19, 2026 9 min read

Imagine unpacking a whole list in a single line of code.

Or receiving multiple values from a function without any hassle.

What if you could merge lists or dictionaries with just a single asterisk?

This is the power of unpacking.

It’s all about deconstructing elements, and today, we’ll master it from the ground up.

We’ll start with simple examples and gradually move to more complex scenarios.

The Basics of Unpacking

Unpacking means taking elements from an iterable, like a list, and assigning them to variables.

Let’s say we have a list of numbers.

numbers = [10, 20, 30]

We can assign these values to variables a, b, and c.

a, b, c = numbers

Python is smart enough to know that a should be 10, b should be 20, and c should be 30.

[!WARNING] The variables must always be on the left side of the assignment. You can’t do numbers = a, b, c, as that would overwrite your original list.

The key rule is that the number of variables must exactly match the number of items in the list.

If we print them, we get the expected values.

print(a) # 10
print(b) # 20
print(c) # 30

Python neatly distributes the list’s values to the variables in order.

This works for any iterable, like a tuple.

point = (5, 8)
x, y = point

print(x) # 5
print(y) # 8

Again, the number of variables must match the number of values.

Ignoring Values with Underscore

What if you only care about certain values?

You can use an underscore _ as a placeholder for values you want to ignore.

Consider this list:

numbers = [100, 200, 300]

Let’s say we only want the first and last values.

We can assign the middle value to an underscore.

first, _, last = numbers

print(first) # 100
print(last)  # 300

Here, we’re telling Python we don’t need the value 200.

We’re not interested in it, so we discard it.

This keeps our code clean and signals our intent clearly.

The Power of the Star Operator (*)

Now, what if you have more values than variables?

This is where the star operator (*) shines.

It gathers all the “leftover” items into a new list.

Let’s look at this list with five numbers.

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

We can assign the first item to a and everything else to b.

a, *b = numbers

print(f"a is: {a}")
print(f"b is: {b}")

The output shows a gets the first value, and b becomes a list of the rest.

a is: 1
b is: [2, 3, 4, 5]

The star operator is greedy; it collects everything it can.

You can also use it to grab items in the middle.

numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers

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

Without the star, Python would throw an error because we have three variables but five values.

The star says: “Assign first and last normally, and I’ll take everything in between.”

It’s a powerful way to handle lists of unknown or variable length.

Unpacking in Function Calls

The star operator is also incredibly useful for function arguments.

Let’s define a simple function that adds three numbers.

def add(a, b, c):
  return a + b + c

Now, we have a list of numbers we want to pass to this function.

numbers = [10, 20, 30]

If you pass the list directly, you’ll get an error.

Python sees the list as a single argument (a) and complains that b and c are missing.

The solution is to unpack the list with the star operator.

result = add(*numbers)
print(result) # 60

The *numbers syntax tells Python to unpack the list and pass its elements as separate arguments.

It’s equivalent to calling add(10, 20, 30).

Unpacking Dictionaries with **

Dictionaries have a special unpacking operator: the double-star (**).

This is because dictionaries have both keys and values.

One star is for lists (values only), two stars are for dictionaries (key-value pairs).

Let’s create a function that prints a student’s name and age.

def print_student(name, age):
  print(f"Name: {name}, Age: {age}")

And here’s our student data in a dictionary.

student_data = {"name": "Ali", "age": 20}

Just like with lists, passing the dictionary directly won’t work.

You need to unpack it with **.

print_student(**student_data)

This unpacks the dictionary into keyword arguments, matching the keys to the function’s parameter names.

The output is exactly what we want.

Name: Ali, Age: 20

Think of the ** operator as breaking a necklace and letting all the beads (key-value pairs) scatter into the function.

Merging Iterables

Unpacking is also fantastic for merging lists and dictionaries.

Merging Lists

Let’s say you have two lists.

list1 = [1, 2]
list2 = [3, 4]

You can combine them into a single, flat list using the star operator.

merged_list = [*list1, *list2]
print(merged_list) # [1, 2, 3, 4]

Without unpacking, you’d get a nested list: [[1, 2], [3, 4]].

The star operator unpacks each list’s elements before creating the new one.

Merging Dictionaries

The same principle applies to dictionaries with the double-star operator.

dict1 = {'a': 1}
dict2 = {'b': 2}

Merge them like this:

merged_dict = {**dict1, **dict2}
print(merged_dict) # {'a': 1, 'b': 2}

[!TIP] If both dictionaries have the same key, the value from the last dictionary in the expression will win.

This is a clean and highly readable way to combine dictionaries.

More Unpacking Tricks

Swapping Variables

Unpacking provides a Pythonic way to swap two variables without a temporary variable.

a = 5
b = 10

# The swap
a, b = b, a

print(f"a is now: {a}") # 10
print(f"b is now: {b}") # 5

It’s concise, readable, and efficient.

Unpacking in Loops

You can also use unpacking directly in for loops.

This is perfect for iterating over a list of tuples or lists.

points = [(1, 2), (3, 4), (5, 6)]

for x, y in points:
  print(f"Sum of ({x}, {y}) is {x + y}")

On each iteration, Python unpacks the tuple into x and y.

The output shows the sum for each pair.

Sum of (1, 2) is 3
Sum of (3, 4) is 7
Sum of (5, 6) is 11

Summary

Unpacking is a fundamental feature in Python that makes your code cleaner and more expressive.

mindmap
  root((Unpacking))
    Basics
      ::icon(fa fa-list)
      Assigning list items to variables
      `a, b, c = [1, 2, 3]`
    Ignoring Values
      ::icon(fa fa-eye-slash)
      Use underscore `_`
      `a, _, c = [1, 2, 3]`
    Star Operator `*`
      ::icon(fa fa-star)
      Gather remaining items
      `a, *b = [1, 2, 3, 4]`
      Merge lists
      `[*list1, *list2]`
      Function arguments
      `func(*my_list)`
    Double-Star `**`
      ::icon(fa fa-star)
      Merge dictionaries
      `{**dict1, **dict2}`
      Function keyword arguments
      `func(**my_dict)`
    Common Uses
      ::icon(fa fa-cogs)
      Swapping variables
      `a, b = b, a`
      `for` loops
      `for x, y in points:`

Use it when you receive complex data, when a function returns multiple values, or when you need to write clean, professional code.


Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?