1

I was curious about the way this

for _ in range(10): #1

loop#1 execution is different from

for i in range(10): #2

loop#2 execution. They certainly do look exactly the same, but, I wanted to have a clear understanding and know if their functioning under the hood is also exactly the same? Also, I know when both these types of loops are used, so, I am not looking for an answer to "When to use What?".

I had already read this question, but, it doesn't provide a clear distinction and the working of the two under the hood.

AK47
  • 7,795
  • 6
  • 33
  • 57
Satya
  • 627
  • 6
  • 22
  • 2
    Possible duplicate of [What is the purpose of the single underscore "\_" variable in Python?](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) – Fukiyel Feb 23 '19 at 15:03

2 Answers2

4

They both do the exact same thing

The former is used if the variable is disposable and not usually referenced in the loop

for _ in range(10): #1

The latter is used if you plan to reference the variable name within the loop

for i in range(10): #2

It's boils down to the python naming convention -- under the hood, both loops function in the exact same way

AK47
  • 7,795
  • 6
  • 33
  • 57
1

in python the underscore character it's a valid var name, so bot snippets are the same but with different var names, like @AK47 says, use de under score if you don't want use the var inside the loop, but the _ it's a valid var name so you can used inside the loop:

enter image description here

some frameworks like django use the underscore in their code patterns:

enter image description here

Gytree
  • 517
  • 2
  • 13