Skip to content

Instantly share code, notes, and snippets.

@farukyildiz
Last active January 30, 2024 17:18
Show Gist options
  • Save farukyildiz/9aa7bf446f082538ff17077ceb14bbd6 to your computer and use it in GitHub Desktop.
Save farukyildiz/9aa7bf446f082538ff17077ceb14bbd6 to your computer and use it in GitHub Desktop.
[Python] - immutable vs mutable
# immutable: no changes are allowed after the object is created.
# string, integer, float, decimal, boolean, tuples, frozen sets, rational, complex
year = "2023"
mem_address = id(year)
print(f"[years] memory address: {mem_address}")
# output: 140065542357616
# a new object is created by assigning the value 2024 to the year variable.
year = "2024"
mem_address = id(year)
print(f"[years] memory address: {mem_address}")
# output: 140065542414064
# mutables: change is allowed after the object is created.
# list, set, dict
years = ["2020", "2021", "2022", "2023"]
mem_address = id(years)
print(f"[years] memory address: {mem_address}")
# output: 140065542285632
years.append("2024")
mem_address = id(years)
print(f"[years] memory address: {mem_address}")
# output: 140065542285632
# Note: Get value through memory address
import ctypes
age = 18
mem_address = id(age)
age = 19
print(f"new age: {age}")
old_age = ctypes.cast(mem_address, ctypes.py_object).value
print(f"old age: {old_age}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment