Skip to content

Instantly share code, notes, and snippets.

@sungiven
Created February 10, 2024 09:35
Show Gist options
  • Save sungiven/241fa5bd6594afd44be0d109f99783e0 to your computer and use it in GitHub Desktop.
Save sungiven/241fa5bd6594afd44be0d109f99783e0 to your computer and use it in GitHub Desktop.
genexp init vs listcomp
#!/usr/bin/env python3
symbols = "$¢£¥€¤"
output = tuple(ord(symbol) for symbol in symbols)
print(output)
# If the generator expression is the single argument in a function call, there is no
# need to duplicate the enclosing parentheses.
import array
output = array.array("I", (ord(symbol) for symbol in symbols))
print(output)
# The array constructor takes two arguments, so the parentheses around the gen‐
# erator expression are mandatory. The first argument of the array constructor
# defines the storage type used for the numbers in the array.
colors = ["black", "white"]
sizes = ["S", "M", "L"]
for tshirt in (f"{c} {s}" for c in colors for s in sizes):
print(tshirt)
# The generator expression yields items one by one; a list with all six T-shirt varia‐
# tions is never produced.
"""
To initialize tuples, arrays, and other types of sequences, you could start from a
listcomp, but a genexp (generator expression) saves memory because it yields items
one by one using the iterator protocol instead of building a whole list just to feed
another constructor.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment