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? ๐