Skip to content

Instantly share code, notes, and snippets.

@savanne-kham
Last active February 23, 2023 21:29
Show Gist options
  • Select an option

  • Save savanne-kham/a06e261ecd13b4a33775b39925038a50 to your computer and use it in GitHub Desktop.

Select an option

Save savanne-kham/a06e261ecd13b4a33775b39925038a50 to your computer and use it in GitHub Desktop.
Genexp saves memory and computation by yielding items one by one using the iterator protocol instead of building a whole list and feeding another constructor
symbols = 'ABCDE'
genexp_tuple = tuple(ord(symbol) for symbol in symbols)
print(f"{genexp_tuple}")
import array
# parenthesis around second arg is mandatory for genexp arg
genexp_array = array.array('I', (ord(symbol) for symbol in symbols))
print(f"{genexp_array}")
# cartesian product that doesn't swarm memory as genexp yield results 1by1
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in (f'{c} {s}' for c in colors for s in sizes):
print(tshirt)
# genexp are usefull to generate output that doesn't need to be kept
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment