Understanding for __ in range(n) in Python: Why and When to Use It

Python is known for its readability and simplicity. But sometimes, you’ll come across code that seems unusual, like ...

for __ in range(3):
    print("Hello World")

So, what exactly _ (underscore) is doing in the above script.

What Does for __ in range(3) Mean?

In Python, when you write a loop like:

for i in range(3):
    print(i)

The variable i takes on the values 0, 1, and 2, One at a time and print it. But if you don't want to print i and just print "Hello World", then ? Do we really need i ?.

That’s where _ or __ comes in!

In Python, _ (underscore) is commonly used as a “throwaway variable” — a variable you don't plan to use.

Using __ (double underscore) is similar but less common and often used to avoid clashes with other variables.

When Should You Use __?

  • You're writing quick scripts or tests.
  • You’re inside a nested loop and want to avoid reusing _.
  • You want to make it very clear that the loop variable is not being used at all.

You can also write the above script like

print(['Hello World' for _ in range(3)])

It is very useful and using underscore in the code makes the code easier to understand, avoids unnecessary variable declaration, and makes the code beautiful.