Skip to content

Instantly share code, notes, and snippets.

@carsongee
Last active August 29, 2015 14:24
Show Gist options
  • Save carsongee/d6a34da47346d082f158 to your computer and use it in GitHub Desktop.
Save carsongee/d6a34da47346d082f158 to your computer and use it in GitHub Desktop.
Python For loop vs in
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())
@carsongee
Copy link
Author

My results:

Timeit for `in`
7.78765392303
Timeit for `for` loop
35.9058320522

@giocalitri
Copy link

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