Last active
August 29, 2015 14:24
-
-
Save carsongee/d6a34da47346d082f158 to your computer and use it in GitHub Desktop.
Python For loop vs in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def x_in_loop(): | |
x = range(500) | |
for i in x: | |
if x == 253: | |
return True | |
return False | |
def x_in_range(): | |
x = range(500) | |
return 253 in x | |
if __name__=='__main__': | |
from timeit import Timer | |
timer = Timer("x_in_range()", "from __main__ import x_in_range") | |
print("Timeit for `in`") | |
print(timer.timeit()) | |
timer = Timer("x_in_loop()", "from __main__ import x_in_loop") | |
print("Timeit for `for` loop") | |
print(timer.timeit()) |
I don't think it's a fair comparison in python, since the in
statement (if the __contains__
method is not defined) uses by default is a function compiled in c (from my research _PySequence_IterSearch()
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My results: