0
0
PythonConceptBeginner · 3 min read

What is Single Underscore in Python: Meaning and Usage

In Python, a single underscore _ is a convention used to indicate a temporary or insignificant variable, often in loops or unpacking. It can also hold the result of the last expression in interactive sessions like the Python shell.
⚙️

How It Works

The single underscore _ in Python is like a placeholder or a 'throwaway' name. Imagine you are sorting through items but only care about some of them; the underscore is a way to say "I don't need this value." It tells other programmers that this variable is temporary or unimportant.

In interactive Python shells, _ automatically stores the result of the last expression you typed. This is like a quick memory slot for your last answer, so you can reuse it without assigning a new variable name.

💻

Example

This example shows using _ as a throwaway variable in a loop and how it stores the last result in the Python shell.

python
for _ in range(3):
    print("Hello!")

# In an interactive shell:
result = 5 + 7
print(result)  # prints 12
print(_)       # prints 12, the last expression result
Output
Hello! Hello! Hello! 12 12
🎯

When to Use

Use a single underscore when you need a variable but don't plan to use it later. For example, in loops where the index is irrelevant or when unpacking tuples but only some values matter.

In interactive sessions, you can use _ to quickly access the last result without assigning it a name, which speeds up quick calculations or tests.

This keeps your code clean and signals to others that some values are intentionally ignored.

Key Points

  • Single underscore is a naming convention for unused or temporary variables.
  • In interactive shells, _ holds the last expression's result.
  • It helps keep code readable by showing which variables are unimportant.
  • It is not a special keyword but a strong community practice.

Key Takeaways

Use _ as a throwaway variable when you don't need a value.
In Python shells, _ stores the last expression result automatically.
Using _ improves code readability by marking ignored variables.
The single underscore is a convention, not a language-enforced rule.