Understanding _ in range() in Python

In Python, when you see a loop like this:

for _ in range(5):
    print("Hello")

๐Ÿ”น Output:

Hello
Hello
Hello
Hello
Hello

1. What Does _ Mean in for _ in range()?

The underscore (_) is a throwaway variable or dummy variable in Python. It means:
๐ŸŸข “I donโ€™t care about this variable, I just need to repeat the loop.”

So, instead of writing:

for i in range(5):  # i is not used
    print("Hello")

You use _ to indicate that the loop variable is irrelevant.


2. When to Use _ in range()?

You use _ when you donโ€™t need the loop variable inside the loop. Some common cases:

๐Ÿ”น Example 1: Running a Loop a Fixed Number of Times

for _ in range(3):
    print("Python is fun!")

Output:

Python is fun!
Python is fun!
Python is fun!

โœ” The loop runs 3 times, and _ is ignored.


๐Ÿ”น Example 2: Creating a List of Random Numbers

import random

random_numbers = [random.randint(1, 100) for _ in range(5)]
print(random_numbers)

โœ” _ is used because the loop variable is not needed.


๐Ÿ”น Example 3: Taking Multiple Inputs

n = int(input("Enter number of students: "))

students = [input("Enter student name: ") for _ in range(n)]
print(students)

โœ” The loop runs n times to collect n names, but we donโ€™t use the loop variable.


๐Ÿ”น Example 4: Nested Loops (Printing a Pattern)

for _ in range(3):
    for _ in range(5):
        print("*", end=" ")
    print()

Output:

* * * * *
* * * * *
* * * * *

โœ” _ is used in both loops since we only care about repetitions.


3. When NOT to Use _ in range()

โŒ If you need to use the loop variable, donโ€™t use _.
For example:

for i in range(5):  # We need 'i' here
    print("Iteration:", i)

โœ” Here, i is useful, so _ should not be used.


4. Summary

  • _ is used when the loop variable is not needed.
  • It is just a convention; you can replace _ with any other name.
  • It improves code readability by indicating that the variable is not important.

Would you like more examples? ๐Ÿš€