Skip to content

Instantly share code, notes, and snippets.

@sungiven
Created January 27, 2024 10:29
Show Gist options
  • Save sungiven/ee622109d04a240f100b8a1f4fa85780 to your computer and use it in GitHub Desktop.
Save sungiven/ee622109d04a240f100b8a1f4fa85780 to your computer and use it in GitHub Desktop.
local scope in comps and gen exps
#!/usr/bin/env python3
x = "EGG"
codes = [ord(x) for x in x]
print(codes)
# output: [69, 71, 71]
print(x)
# x is not clobbered, still bound to 'EGG'
# output: EGG
codes = [last := ord(c) for c in x]
print(last)
# `last` remains
# output: 71
print(c)
# but `c` is gone; it only existed inside the listcomp
# output: NameError: name 'c' is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment