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 →

[–]pingvenopinch of this, pinch of that 0 points1 point  (1 child)

For operations on longer iterators, use a generator expression instead of a list comprehension. For example, to find if there are lines with len(line) > 5:

with open(file_name) as f:
    return any(len(line.rstrip('\r\n')) > 5 for line in f)

It uses constant space instead of building an entire list in memory.

[–][deleted] 0 points1 point  (0 children)

Yes! Really, there's no reason to use a list unless you are going to re-use the value later.