DEV Community

BHUVANESH M
BHUVANESH M

Posted on • Edited on

UnderScore in for loop in Python

Image description
Imagine you're coding away and you suddenly write:

for _ in range(5):
    print("Hello World!")
Enter fullscreen mode Exit fullscreen mode

Have you done this before? If not, you're about to discover a little Python magic!


๐Ÿ“š Once Upon a Loop...

There was a coder who loved saying "Hello World!". They wanted to print it five times but didnโ€™t care about which turn it was โ€” first, second, fifth, didnโ€™t matter. So instead of using the classic i, they used a mysterious symbol: _.

Letโ€™s dive into why that's not only okay but actually pretty smart.


๐Ÿ› ๏ธ The Code:

for _ in range(5):
    print("Hello World!")
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” What's Happening Here?

1. The Power of for Loops

Think of a for loop like a magical spell: "Do this action again and again until I say stop."

Normally, you loop through items (like numbers, letters, or lists), and for each item, you do something.

The basic syntax is:

for item in collection:
    # do something
Enter fullscreen mode Exit fullscreen mode

Here, the collection is our iterable โ€” something that can be looped through!

2. The Tale of range(5)

range(5) is like your number generator buddy. It hands you numbers starting from 0, going up to (but not including) 5.

Itโ€™s like whispering:

"Here you go โ€” 0, 1, 2, 3, 4. Use them wisely."

Fun fact: range is super memory-efficient. It doesnโ€™t actually create a full list in memory unless you ask it to!

3. The Mysterious Underscore _

Usually, we name our loop variable i, j, num, etc.

But what if you don't need it?

Thatโ€™s where _ steps in like a ninja ๐Ÿฅท โ€” silent, unnoticed, but doing its job perfectly.

Using _ says:

"Iโ€™m looping, but I don't care about the current number."

Itโ€™s Pythonโ€™s way of keeping your code clean and your intentions clear.

4. What Happens Inside?

Every time the loop runs, it executes:

print("Hello World!")
Enter fullscreen mode Exit fullscreen mode

No matter what invisible number _ is holding, you just get a nice, friendly "Hello World!" printed out.

Since range(5) gives five numbers, you get:

Run Hidden Value (_) What Prints
1 0 Hello World!
2 1 Hello World!
3 2 Hello World!
4 3 Hello World!
5 4 Hello World!

Five "Hello World!"s, and a big smile on your face. ๐Ÿ˜Š


๐ŸŽฏ Moral of the Story:

  • Use _ when you don't need the loop variable.
  • range(n) is perfect for running something n times.
  • Embrace little tricks that make your code cleaner and easier to read.

๐Ÿ“ข Before You Go...

Question for you:

Next time you write a loop, will you use _ like a Python pro? ๐Ÿ


๐Ÿ“– For more tips and tricks in Python ๐Ÿ, check out

Packed with hidden gems, Python's underrated features and modules are real game-changers when it comes to writing clean and efficient code.


Top comments (0)