In Python, is it better to use list comprehensions or for-each loops? In Python, is it better to use list comprehensions or for-each loops? python python

In Python, is it better to use list comprehensions or for-each loops?


If the iteration is being done for its side effect ( as it is in your "print" example ), then a loop is clearer.

If the iteration is executed in order to build a composite value, then list comprehensions are usually more readable.


The particular code examples you have chosen do not demonstrate any advantage of the list comprehension, because it is being (mis-)used for the trivial task of printing. In this simple case I would choose the simple for loop.

In many other cases, you will want to supply an actual list to another function or method, and the list comprehension is the easiest and most readable way to do that.

An example which would clearly show the superiority of the list comp could be made by replacing the print example with one involving creating another actual list, by appending to one on each iteration of the for loop:

L = []for x in range(10):    L.append(x**2)

Gives the same L as:

L = [x**2 for x in range(10)]


I find the first example better - less verbose, clearer and more readable.

In my opinion, go with what best gets your intention across, after all:

Programs should be written for people to read, and only incidentally for machines to execute.

-- from "Structure and Interpretation of Computer Programs" by Abelson and Sussman

By the way, since you're just starting to learn Python, start learning the new String Formatting syntax right away:

for k, v in os.environ.items():    print "{0}={1}".format(k, v)