Which is faster between a list comprehension and using the list()

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Which is faster between a list comprehension and using the list()



Trying to create a list of items using one of these methods:


from pathlib import Path

list_comprehension = [item for item in Path('.').iterdir()]

list_method = list(Path('.').iterdir())



Which is faster and how do I check for speed.





try it like import time; start = time.time();list_comprehension = [item for item in Path('.').iterdir()];end=time.time()-start;print(end)
– Saeed
Aug 12 at 6:56





Use timeit to answer your own question...
– Reut Sharabani
Aug 12 at 7:01


timeit




2 Answers
2



you can use timeit module to achieve it.


timeit


import timeit

first = """
from pathlib import Path

list_comprehension = [item for item in Path('.').iterdir()]
"""

second = """
from pathlib import Path

list_method = list(Path('.').iterdir())
"""

print(timeit.timeit(stmt=first, number=10000))
# 1.0698672000000329
print(timeit.timeit(stmt=second, number=10000))
# 1.0508478000000423



enter image description here





which python are you using that both the results are almost same?
– argo
Aug 12 at 7:14





@argo python3.6.4, maybe it is related to the machine?
– pwxcoo
Aug 12 at 7:16





Thats interesting. can you provide your machine specs?
– argo
Aug 12 at 7:17



Use the following code to check the time


from pathlib import Path
from datetime import datetime
start_time = datetime.now()
list_comprehension = [item for item in Path('.').iterdir()]
print(datetime.now()- start_time)
start_time = datetime.now()
list_method = list(Path('.').iterdir())
print(datetime.now()- start_time)



EDIT:
You should use timeit for better result


import timeit

list_comprehension = '''
from pathlib import Path
a = [item for item in Path('.').iterdir()]'''

list_method = '''
from pathlib import Path
a = list(Path('.').iterdir())'''

print(timeit.timeit(list_comprehension, number=1000))
# 0.10110808495664969
print(timeit.timeit(list_method, number=1000))
# 0.05479578400263563






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS