« Back to Index

Python Generator Expressions

View original Gist on GitHub

Python Generator Expressions.py

(x for x in open('super-large.txt'))  # short-hand syntax for a generator ()
                                      # better performing than a list comprehension []
                                      # which loads everything into memory all at once
                                      
for line in (x for x in open('super-large.txt')):
    pass  # execute once for every line
  
for line in (x for x in open('super-large.txt') if int(x) % 100):
    pass  # execute once every 100 lines (instead of every line)