Skip to content Skip to sidebar Skip to footer

When To Use A List Comprehension Vs A For Loop

Is there a general rule for when a list comprehension is preferred over a for loop? For example: A single for loop is great when converted to a comprehension: l = [] for word in se

Solution 1:

The answer depends on your opinion. However, since I do remember a specific piece of advice of this from an author of a book that is well regarded in the Python community, I can share the following excerpt from the book 'Fluent Python' by Luciano Ramalho:

A for loop may be used to do lots of different things: scanning a sequence to count or pick items, computing aggregates (sums, averages), or any number of other processing tasks. [...] In contrast, a listcomp is meant to do one thing only: to build a new list.

Of course, it is possible to abuse list comprehensions to write truly incomprehensible code. I’ve seen Python code with listcomps used just to repeat a block of code for its side effects.

If you are not doing something with the produced list, you should not use that syntax.

Also, try to keep it short. If the list comprehension spans more than two lines, it is probably best to break it apart or rewrite as a plain old for loop. Use your best judgment: for Python as for English, there are no hard-and-fast rules for clear writing.


Solution 2:

According to this, performance can be gained.

import timeit

def squares(size):
    result = []
    for number in range(size):
        result.append(number*number)
    return result

def squares_comprehension(size):
    return [number*number for number in range(size)]

print(timeit.timeit("squares(50)", "from __main__ import squares", number = 1_000_000))
print(timeit.timeit("squares_comprehension(50)", "from __main__ import squares_comprehension", number = 1_000_000))

5.4292075
4.1652729000000015

Hope this helps.


Solution 3:

I'd add that you could always work with generators and iterators. There is no major memory overhead, but the performance may suffer unless the innermost operation is relatively costly.

from itertools import chain
sentence = "flat is better than nested"

words = sentence.split()
f_words = (w for w in words if w.startswith('f'))
f_chars = chain(*f_words)
good_chars = [c for c in f_chars if c in 'abco']

Post a Comment for "When To Use A List Comprehension Vs A For Loop"