0
0
PythonHow-ToBeginner · 3 min read

How to Use * for Unpacking in Python: Simple Guide

In Python, the * operator is used to unpack iterable objects like lists or tuples into individual elements. It can also unpack arguments when calling functions, spreading them as separate parameters.
📐

Syntax

The * operator is placed before an iterable to unpack its elements. It can be used in assignments, function calls, or inside data structures.

  • *iterable: Unpacks elements from the iterable.
  • In function calls: func(*args) unpacks a list or tuple into separate arguments.
  • In assignments: a, *b, c = [1, 2, 3, 4] unpacks with the middle part collecting remaining elements.
python
numbers = [1, 2, 3]
print(*numbers)  # Unpacks list elements

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

args = (1, 2, 3)
print(add(*args))  # Unpacks tuple as arguments

first, *middle, last = [10, 20, 30, 40]
print(first, middle, last)  # Unpacks with star in assignment
Output
1 2 3 6 10 [20, 30] 40
💻

Example

This example shows how * unpacks a list into separate arguments for a function and how it collects remaining items in a list during assignment.

python
def greet(greeting, name, punctuation):
    print(f"{greeting}, {name}{punctuation}")

words = ["Hello", "Alice", "!"]
greet(*words)  # Unpacks list into function arguments

numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")
Output
Hello, Alice! First: 1 Middle: [2, 3, 4] Last: 5
⚠️

Common Pitfalls

One common mistake is forgetting that * only works with iterables. Trying to unpack a non-iterable raises an error. Also, using * incorrectly in assignments can cause syntax errors.

Another pitfall is mixing *args and **kwargs incorrectly in function calls.

python
def func(a, b, c):
    print(a, b, c)

# Wrong: unpacking a non-iterable
try:
    func(*10)
except TypeError as e:
    print(f"Error: {e}")

# Correct usage
args = [1, 2, 3]
func(*args)
Output
Error: 'int' object is not iterable 1 2 3
📊

Quick Reference

  • Unpack list/tuple in function call: func(*args)
  • Unpack in assignment: a, *b, c = iterable
  • Unpack in list or tuple creation: new_list = [*old_list, 4, 5]
  • Use with dictionaries: {**dict1, **dict2} (for unpacking dicts)

Key Takeaways

Use * to unpack iterables into individual elements or function arguments.
In assignments, * collects multiple elements into a list.
Only use * with iterable objects to avoid errors.
You can combine unpacking with other elements in lists, tuples, and function calls.
For dictionaries, use ** to unpack key-value pairs.