Created
July 18, 2012 23:20
-
-
Save pzelnip/3139645 to your computer and use it in GitHub Desktop.
Counting number of elements in a list that meet criteria
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
from timeit import Timer | |
if __name__ == "__main__": | |
setup = 'x = list(range(100000))' | |
num_iter = 1000 | |
print(Timer('sum(1 for item in x if item % 2 == 0)', setup).timeit(num_iter)) | |
print(Timer('len([item for item in x if item % 2 == 0])', setup).timeit(num_iter)) | |
# prints (on my machine): | |
# 12.4215... | |
# 10.9932... | |
# showing that the len() on a list comp is a bit faster. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment