Because you are running more often in code written in C in the interpretor. i.e. i+=1 is in Python, so slow (comparatively), whereas range(0,...) is one C call the for loop will execute mostly in C too.
Most of Python's built in method calls are run as C code. Code that has to be interpreted is much slower. In terms of memory efficiency and execution speed the difference is gigantic. The python internals have been optimized to the extreme, and it's best to take advantage of those optimizations.
I think the answer here is a little more subtle than the other answers suggest, though the gist of it is correct: the for loop is faster because more of the operations happen in C and less in Python.
More specifically, in the for loop case, two things happen in C that in the while loop are handled in Python:
In the while loop, the comparison i < 100000000 is executed in Python, whereas in the for loop, the job is passed to the iterator of range(100000000), which internally does the iteration (and hence bounds check) in C.
In the while loop, the loop update i += 1 happens in Python, whereas in the for loop again the iterator of range(100000000), written in C, does the i+=1 (or ++i).
We can see that it is a combination of both of these things that makes the for loop faster by manually adding them back to see the difference.
import timeit
N = 100000000
def while_loop():
i = 0
while i < N:
i += 1
def for_loop_pure():
for i in range(N):
pass
def for_loop_with_increment():
for i in range(N):
i += 1
def for_loop_with_test():
for i in range(N):
if i < N: pass
def for_loop_with_increment_and_test():
for i in range(N):
if i < N: pass
i += 1
def main():
print('while loop\t\t', timeit.timeit(while_loop, number=1))
print('for pure\t\t', timeit.timeit(for_loop_pure, number=1))
print('for inc\t\t\t', timeit.timeit(for_loop_with_increment, number=1))
print('for test\t\t', timeit.timeit(for_loop_with_test, number=1))
print('for inc+test\t', timeit.timeit(for_loop_with_increment_and_test, number=1))
if __name__ == '__main__':
main()
I tried this both with the number 100000000 a literal constant and with it being a variable N as would be more typical.
# inline constant N
while loop 3.5131139
for pure 1.3211338000000001
for inc 3.5477727000000003
for test 2.5209639
for inc+test 4.697028999999999
# variable N
while loop 4.1298240999999996
for pure 1.3526357999999998
for inc 3.6060175
for test 3.1093069
for inc+test 5.4753364
As you can see, in both cases, the while time is very close to the difference of for inc+test and for pure. Note also that in the case where we use the N variable, the while has an additional slowdown to repeatedly lookup the value of N, but the for does not.
It's really crazy that such trivial modifications can result in over 3x code speedup, but that's Python for you. And don't even get me started on when you can use a builtin over a loop at all....