Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of a list comprehension over a for 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?

like image 376
David Avatar asked May 02 '13 15:05

David


People also ask

Is list comprehension better than for loop?

Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.

What are the advantages of list comprehension?

List comprehension is great for creating new lists for many reasons: The code is more concise. The code is generally more readable. The code, in most cases, will run faster.

Why are list comprehension faster than for loops?

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.

What is the advantage of use list comprehension in Python?

One main benefit of using a list comprehension in Python is that it's a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. You don't have to use a different approach for each scenario.


1 Answers

List comprehensions are more compact and faster than an explicit for loop building a list:

def slower():     result = []     for elem in some_iterable:         result.append(elem)     return result  def faster():     return [elem for elem in some_iterable] 

This is because calling .append() on a list 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 the list to fit the elements in one go:

>>> some_iterable = range(1000) >>> import timeit >>> timeit.timeit('f()', 'from __main__ import slower as f', number=10000) 1.4456570148468018 >>> timeit.timeit('f()', 'from __main__ import faster as f', number=10000) 0.49323201179504395 

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.

like image 71
Martijn Pieters Avatar answered Oct 04 '22 10:10

Martijn Pieters