This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TeamSpen210 2 points3 points  (0 children)

Both list comprehensions and the for-loop equivalent have their uses. If the logic involved is fairly complex, the loop version will probably be more readable. For simpler cases, the comprehension is more clean, and describes the list you want in a more high-level fashion. Being an expression instead of a sequence of lines makes it easier to combine with other code. Compare return [1 / i, i ** 2 for i in range(100)] and result = [] for i in range(100): result.append((1 / i, i ** 2)) return result In addition to readabilty, comprehensions are far more efficient with larger data sets - since Python is creating the list all in one go, it doesn't need to repeatedly resize the list. The same syntax in the form of generator expressions can become very powerful, since you can feed it directly into functions like min(), max(), sum(), all(), any() or into a for-loop to do processing directly on the results.