Search code examples
pythonpython-3.xfor-looppython-2.xconventions

Difference between similar looking Python for-loops?


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.


Solution

  • 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