What is the advantage of using a list comprehension over a for
loop in Python?
Is it mainly to make it more humanly readable, or are there other reasons to use a list comprehension instead of a loop?
What is the advantage of using a list comprehension over a for
loop in Python?
Is it mainly to make it more humanly readable, or are there other reasons to use a list comprehension instead of a loop?
List comprehensions are more compact and faster than an explicit
for
loop building a list:This is because calling
.append()
on alist
causes the list object to grow (in chunks) to make space for new elements individually, while the list comprehension gathers all elements first before creating thelist
to fit the elements in one go:However, this does not mean you should start using list comprehensions for everything! A list comprehension will still build a list object; if you are using a list comprehension just because it gives you a one-line loop, think again. You are probably wasting cycles building a list object that you then discard again. Just stick to a normal
for
loop in that case.