Skip to content

Instantly share code, notes, and snippets.

@shenoy-anurag
Created July 14, 2021 13:46
Show Gist options
  • Save shenoy-anurag/9054082f4d13d8fc586b0cfdac166631 to your computer and use it in GitHub Desktop.
Save shenoy-anurag/9054082f4d13d8fc586b0cfdac166631 to your computer and use it in GitHub Desktop.
Mutable vs Immutable Objects in Python
"""
Mutable vs Immutable objects in Python
"""
# Numbers are immutable
a = 10
b = a
b += 1
print(a, b)
# Memory "locations" of numerical values
a = 10
b = a
print(hex(id(a)))
print(id(b))
b = b + 1
print(id(b))
# Strings are immutable too!
s = "I love icecream."
print(s)
print(hex(id(s)))
s = s + " I also like mangoes."
print(s)
print(hex(id(s)))
# Special values are also immutable, but not in the way you think.
a = None
print(hex(id(a)))
a = True
print(hex(id(a)))
a = False
print(hex(id(a)))
a = True
print(hex(id(a)))
a = None
print(hex(id(a)))
# Dictionaries are mutable objects
a = {'name': 'Raj', 'interests': ['computer science', 'music', 'astronomy']}
print(hex(id(a)))
a['age'] = 25
print(a)
print(hex(id(a)))
# Be careful with two names referring to the same mutable object
a = {'a': 1}
b = a
b['a'] = 2
print(a)
print(b)
# Datetime example
import datetime
new_date = datetime.datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
print(new_date)
print(hex(id(new_date)))
new_date = new_date.replace(year=2049)
print(new_date)
print(hex(id(new_date)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment