简体   繁体   中英

python:loop vs comprehension [duplicate]

This question already has an answer here:

I was trying to do some simple procedures using lists. From the book learning python I saw the method of using a comprehension. Well I also knew that a loop could replace it. Now I really want to know that which is faster, loop or comprehension. These are my programs.

a = []
for x in range(1, 101):
    a.append(x)

This would set a as [1, 2, 3, ......, 99, 100]

Now this is what I have done with the comprehension.

[x ** 2 for x in a]

This is what I did with the loop.

c = []
for x in a:
    b=[x**2]
    c+=b

Could any one say a way to find which of the above is faster.Please also try to explain that how comprehensions differ from loops. Any help is appreciated.

You can use the timeit library, or just use time.time() to time it yourself:

>>> from time import time
>>> def first():
...     ftime = time()
...     _foo = [x ** 2 for x in range(1, 101)]
...     print "First", time()-ftime
... 
>>> def second():
...     ftime = time()
...     _foo = []
...     for x in range(1, 101):
...             _b=[x**2]
...             _foo+=_b
...     print "Second", time()-ftime
... 
>>> first()
First 5.60283660889e-05
>>> second()
Second 8.79764556885e-05
>>> first()
First 4.88758087158e-05
>>> second()
Second 8.39233398438e-05
>>> first()
First 2.8133392334e-05
>>> second()
Second 7.29560852051e-05
>>> 

Evidently, the list comprehension runs faster, by a factor of around 2 to 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM