0
0
PythonHow-ToBeginner · 3 min read

How to Ignore Values When Unpacking in Python

In Python, you can ignore values when unpacking by assigning them to the underscore _ variable, which is a common convention for unused values. For example, a, _, c = (1, 2, 3) assigns 1 to a, ignores 2, and assigns 3 to c.
📐

Syntax

When unpacking a sequence, use _ as a placeholder for values you want to ignore. This tells Python you don't need that value.

  • a, _, c = sequence: assigns first and third values, ignores the second.
  • You can use multiple underscores to ignore multiple values.
python
a, _, c = (1, 2, 3)
print(a)
print(c)
Output
1 3
💻

Example

This example shows unpacking a tuple with three values but ignoring the middle one using _. Only the first and last values are kept.

python
data = (10, 20, 30)
a, _, c = data
print(f"First: {a}")
print(f"Ignored middle value")
print(f"Last: {c}")
Output
First: 10 Ignored middle value Last: 30
⚠️

Common Pitfalls

Some common mistakes when ignoring values:

  • Using a named variable instead of _ will keep the value, which may confuse readers.
  • Using _ multiple times in the same scope can overwrite previous ignored values.
  • For ignoring multiple values, use multiple underscores like _, _, c = (1, 2, 3).
python
x, y, z = (1, 2, 3)  # Wrong if you want to ignore y
print(x, z)

_, _, z = (1, 2, 3)  # Correct to ignore first two
print(z)
Output
1 3 3
📊

Quick Reference

PatternDescription
a, _, c = sequenceIgnore the middle value
_, b, _ = sequenceIgnore first and last values, keep middle
_, _, c = sequenceIgnore first two values, keep last
a, *_, c = sequenceIgnore all middle values, keep first and last

Key Takeaways

Use underscore (_) to ignore unwanted values when unpacking sequences.
Multiple underscores can ignore multiple values in order.
Avoid using named variables if you want to clearly ignore values.
Using * with _ can ignore multiple middle values in unpacking.
Ignoring values improves code readability by showing intent clearly.