python - What is the advantage of a list comprehension over a for loop? -
what advantage of using list comprehension on for
loop in python?
is make more humanly readable, or there other reasons use list comprehension instead of loop?
list comprehensions more compact and faster explicit for
loop building list:
def slower(): result = [] elem in some_iterable: result.append(elem) return result def faster(): return [elem elem in some_iterable]
this because calling .append()
on list
causes list object grow (in chunks) make space new elements individually, while list comprehension gathers elements first before creating list
fit elements in 1 go:
>>> some_iterable = range(1000) >>> import timeit >>> timeit.timeit('f()', 'from __main__ import slower f', number=10000) 1.4456570148468018 >>> timeit.timeit('f()', 'from __main__ import faster f', number=10000) 0.49323201179504395
Comments
Post a Comment