Member-only story

Do more with underscores in Python

Allwin Raju
2 min readJan 1, 2025

--

In Python, underscores (_) serve as versatile placeholders in various coding scenarios. They’re handy when iterating through loops, unpacking data, or handling values you don’t need to reference. Let’s dive into some practical examples to see how underscores can simplify your Python code.

Read for free: https://allwin-raju.medium.com/do-more-with-underscores-in-python-7f5aa4f54789?sk=9b0da837030abf3aeb5ae06e7b9893a2

1. Looping a Fixed Number of Times

When you need to repeat an action a specific number of times but don’t care about the loop variable, an underscore is a perfect choice:

for _ in range(5):
print("This will print 5 times")

Here, _ acts as a throwaway variable, indicating you’re not interested in the loop index.

2. Ignoring Specific Values During Enumeration

The enumerate function provides both the index and the value of an iterable. If you only need the value, use _ to ignore the index:

items = ["apple", "banana", "cherry"]
for _, item in enumerate(items):
print(item) # Ignores the index

This approach keeps the code clean and focused on the values you care about.

3. Unpacking Tuples…

--

--

Responses (1)