+ 1

Which one is faster?

Comprehension vs Generation Expression G=[c * 4 for c in "name"] #list comprehension G=(c * 4 for c in "name") #generator expression G=list(G)

5th Jul 2017, 11:08 AM
Mahir Mahbub Srizon
Mahir Mahbub Srizon - avatar
2 Réponses
+ 7
In terms of speed list comprehension is faster: import timeit def m1(): return [c * 4 for c in "name"] def m2(): return list(c * 4 for c in "name") timeit.timeit(m1, number = 100000) 0.11164118750606707 timeit.timeit(m2, number = 100000) 0.20338840264500302 This is also true for larger iterations: def m1(): return [c * 4 for c in range(10000)] def m2(): return list(c * 4 for c in range(10000)) timeit.timeit(m1, number = 100000) 132.59986820312798 timeit.timeit(m2, number = 100000) 188.7506580221831 That being said, for very large iterations generators have an advantage in memory usage, because while the list is created in its entirety right away, a generator will simply iterate through every element on the fly, so you can use it for virtually infinite sequences.
5th Jul 2017, 2:28 PM
Maya
Maya - avatar
+ 2
Agree with @Maya, sometimes you do not need a list but just as intermediate to get result from the list, say sum of the list values, or what ever, then you should definitely use just generator, like sum( k for k in range(101) ), rather than sum( [ k for k in range(101) ] )
5th Jul 2017, 3:45 PM
yuri