[ 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?
- A simple for-loop is easier to read
- 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