0
0
PythonHow-ToBeginner · 3 min read

How to Unpack List in Python: Simple Syntax and Examples

In Python, you can unpack a list by using the * operator to assign its elements to variables. For example, a, b, *rest = [1, 2, 3, 4] assigns 1 to a, 2 to b, and the remaining elements to rest.
📐

Syntax

To unpack a list, use variables separated by commas on the left side of an assignment, and the list on the right. Use the * operator before a variable to capture multiple elements as a list.

  • a, b, c = [1, 2, 3] assigns each element to a variable.
  • a, *rest = [1, 2, 3, 4] assigns first element to a and the rest to rest.
python
a, b, c = [1, 2, 3]
a, *rest = [1, 2, 3, 4]
💻

Example

This example shows unpacking a list into variables and using the * operator to capture remaining elements.

python
numbers = [10, 20, 30, 40, 50]
first, second, *others = numbers
print(f"First: {first}")
print(f"Second: {second}")
print(f"Others: {others}")
Output
First: 10 Second: 20 Others: [30, 40, 50]
⚠️

Common Pitfalls

One common mistake is trying to unpack a list into fewer variables than elements without using *, which causes an error. Also, using * more than once in the same unpacking is not allowed.

python
# Wrong: too many values to unpack
# a, b = [1, 2, 3]  # Raises ValueError

# Correct:
a, b, c = [1, 2, 3]

# Wrong: multiple starred expressions
# a, *b, *c = [1, 2, 3, 4]  # SyntaxError

# Correct:
a, *b, c = [1, 2, 3, 4]
📊

Quick Reference

  • Use * to capture multiple elements as a list.
  • Only one starred expression is allowed per unpacking.
  • Number of variables without * must match list elements count.

Key Takeaways

Use the * operator to unpack multiple list elements into one variable as a list.
Ensure the number of variables matches the list length unless using * to capture extras.
Only one starred variable is allowed in a single unpacking assignment.
Unpacking helps assign list elements to variables cleanly and clearly.
Avoid unpacking errors by matching variables and list elements properly.