Last active
February 23, 2023 21:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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