Skip to content

Instantly share code, notes, and snippets.

@sungiven
Created February 25, 2024 10:08
Show Gist options
  • Save sungiven/e709b6fcda47725018749c6939b8105b to your computer and use it in GitHub Desktop.
Save sungiven/e709b6fcda47725018749c6939b8105b to your computer and use it in GitHub Desktop.
tuples as records and immutable lists
#!/usr/bin/env python3
# tuples as records & immutable lists
## TUPLES AS RECORDS ##
lax_coordinates = (33.9425, -118.408056)
city, year, pop, chg, area = ("Tokyo", 2003, 32_450, 0.66, 8014)
traveler_ids = [("USA", "31195855"), ("BRA", "CE342567"), ("ESP", "XDA205856")]
# the % formatting operator understands tuples and treats each item as a separate
# field.
for passport in sorted(traveler_ids):
print("%s/%s" % passport)
# BRA/CE342567
# ESP/XDA205856
# USA/31195855
# the for loop knows how to retrieve the items of a tuple separately—this is called
# "unpacking." here we are not interested in the second item, so we assign it to _, a
# dummy variable.
for country, _ in traveler_ids:
print(country)
# USA
# BRA
# ESP
## TUPLES AS IMMUTABLE LISTS ##
# even though immutable, the last item is mutable.
a = (1, "egg", [2, 3])
b = (1, "egg", [2, 3])
print(a == b)
# True
a[-1].append(4)
print(a == b)
# False
# function to explicitly determine whether a tuple has fixed value
def fixed(o):
try:
hash(o)
except TypeError:
return False
return True
a = (1, "egg", [2, 3])
b = (1, "egg", (2, 3))
print(fixed(a))
# False
print(fixed(b))
# True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment