Im trying to find the effeciency of list comprehension but it look like its more expensive than a normal function operation. Can someone explain?
def squares(values):
lst = []
for x in range(values):
lst.append(x*x)
return lst
def main():
t = timeit.Timer(stmt="lst = [x*x for x in range(10)]")
print t.timeit()
t = timeit.Timer(stmt="squares",setup="from __main__ import squares")
print t.timeit()
lst = [x*x for x in range(10)]
print lst
print squares(10)
----Output:---
2.4147507644
0.0284455255965
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
For the same output, the normal function calculates in very less time compared to the list comprehension.
I thought the list comprehension is more effecient.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…