Home > database >  Getting different values in for loop when using (_) and (i)
Getting different values in for loop when using (_) and (i)

Time:02-05

I'm new to coding and I am wondering if someone could explain to me why I get different values when using "for i in range ()" compared to "for _ in range ()". When I execute:

for i in range (64):
    i = i * 2
    print(i)    

I get 2,4,6,8,10, etc. But when I run:

i = 1
for _ in range (64):
    i = i * 2
    print(i)   

I get 2,4,8,6,32,64,128, etc. I would expect these values but when I run this with the above code. What's the difference between using (i) and (_)?

CodePudding user response:

In the for i in version, i gets reset to the current step in the range during each iteration step. It's equivalent to:

i = 0
i = i * 2
print(i) # prints 0
i = 1
i = i * 2
print(i) # prints 2
i = 2
i = i * 2
print(i) # prints 4
...

When you using for i in range(...), i doesn't keep any memory of its value from the previous iteration. The range object just returns the next value in the sequence, and this gets assigned to i each time.

But when you use for _ in, you're not assigning the i variable each time. This time it's like:

i = 1
_ = 0
i = i * 2
print(i) # prints 2
_ = 1
i = i * 2
print(i) # prints 4
_ = 2
i = i * 2
print(i) # print 8
...

This time, i keeps its value from the previous iteration, because the range element is being assigned to _ rather than i.

There's nothing special about _, it's an ordinary variable name. But by convention we use this when we need to assign to a variable but aren't going to use it further.

CodePudding user response:

The difference between for i in range(64) and for _ in range(64) is the use of the loop variable.

In for i in range(64), i takes on the values of the numbers in the range from 0 to 63. This means that each time the loop is run, i is updated with the next number in the range.

In for _ in range(64), the loop variable _ is a placeholder that does not receive a value from the range. This is used when you want to run the loop a certain number of times, but you don't need to use the values generated by the range.

In simpler terms, i is used to keep track of the values in the range, while _ is just used to run the loop a certain number of times without using the values generated by the range.

  • Related