Reputation: 711
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.
Upvotes: 1
Views: 46
Reputation: 540
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:
some frameworks like django use the underscore in their code patterns:
Upvotes: 1
Reputation: 9843
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
Upvotes: 4