The underscore in loops
What always confused learning Machine Learning is what I call Python distractions, It distract newbies doing a tutorial or doing a lab or following a code along session and suddenly the author write a line of code that distracts you, it’s a line that you didn’t understand and couldn’t comprehend , your force your mind to forget it, but cant stop thinking, what does he means exactly ? why ?. Before you know it , you usually end up – after some struggle – to quit whatever you are doing and seek to learn what did he do ? and why…are you following ?
In this post, I will share some of the things that python developers take for granted, its usually simple, yet confuses the rest of us… It might be useful for those learning python, or just want to learn some tricks that python can do… here we go, the underscore in loops
example
for _ in range(10):
WHAT ? why use the _ , while you can say
for i in range (10): # or for x in range(10):
why use underscore and not any variable like the rest of us…
well , in some rare cases , you want to iterate over something , in this case range(10) but you don’t want to use the iterator , then you can use underscore aka ‘_’ cause there is no iterator needed. Lets take an example, imagine you want to print the word ‘hello’ 3 times, notice we didn’t use any variable
for _ in range(3):
print(‘hello’)
The output, would look like this
hello
hello
hello
if you want to use a variable, then you would use a variable instead of the underscore , like this
for i in range(3):
print(‘hello’,i)
Output will be
hello 0
hello 1
hello 2
you still with me ? hope that make sense
