Skip to content

Instantly share code, notes, and snippets.

@gwerbin
Created August 9, 2023 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwerbin/a31e5c78b165781e7dad74161e8d7bbd to your computer and use it in GitHub Desktop.
Save gwerbin/a31e5c78b165781e7dad74161e8d7bbd to your computer and use it in GitHub Desktop.
Python "comprehension" expressions
## Lists
result_list_1 = []
for x in xs:
for y in ys:
for z in zs:
if condition(x, y, z):
result_list_1.append((x, y, z))
result_list_2 = [
(x, y, z)
for x in xs
for y in ys
for z in zs
if condition(x, y, z)
]
## Sets
result_set_1 = set()
for x in xs:
for y in ys:
for z in zs:
if condition(x, y, z):
result_set_1.add((x, y, z))
result_set_2 = {
(x, y, z)
for x in xs
for y in ys
for z in zs
if condition(x, y, z)
}
## Dicts
result_dict_1 = {}
for x in xs:
for y in ys:
for z in zs:
if condition(x, y, z):
result_dict_1[(x, y, z)] = func(x, y, z)
result_dict_2 = {
(x, y, z): func(x, y, z)
for x in xs
for y in ys
for z in zs
if condition(x, y, z)
}
## Generators
for make_gen_1():
for x in xs:
for y in ys:
for z in zs:
if condition(x, y, z):
yield (x, y, z)
result_gen_1 = make_gen_1()
result_gen_2 = (
(x, y, z)
for x in xs
for y in ys
for z in zs
if condition(x, y, z)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment