Thursday, February 17, 2011

Python List Comprehensions are not For-loops

I've too frequently seen Python code that looks like this:

[ dosomething(v) for v in items ]

Normally one would write a plain old for-loop:

for v in items:
dosomething(v)

You should always use the latter - not a list comprehension. Why?
  1. A simple for-loop is easier to read
  2. The for-loop does not need to allocate memory for a list that's not even used
The second point is the most important. To repeat the title of this post: A list comprehension is not a for-loop. In worser cases, items may be tied to a database cursor, for example, and could return an arbitrary number of items, so we could potentially allocate excess memory for a very large result set - and all to support a less readable idiom for looping over the result set.

So, don't be tempted by the dark side and confuse list comprehensions with for-loops and your code will be awesome.

0 comments:

Post a Comment