The iron ML notebook
  • The iron data science notebook
  • ML & Data Science
    • Frequent Questions
      • Discriminative vs Generative models
      • Supervised vs Unsupervised learning
      • Batch vs Online Learning
      • Instance-based vs Model-based Learning
      • Bias-Variance Tradeoff
      • Probability vs Likelihood
      • Covariance vs Correlation Matrix
      • Precision vs Recall
      • How does a ROC curve work?
      • Ridge vs Lasso
      • Anomaly detection methods
      • How to deal with imbalanced datasets?
      • What is "Statistically Significant"?
      • Recommendation systems methods
    • Statistics
      • The basics
      • Distributions
      • Sampling
      • IQR
      • Z-score
      • F-statistic
      • Outliers
      • The bayesian basis
      • Statistic vs Parameter
      • Markov Monte Carlo Chain
    • ML Techniques
      • Pre-process
        • PCA
      • Loss functions
      • Regularization
      • Optimization
      • Metrics
        • Distance measures
      • Activation Functions
      • Selection functions
      • Feature Normalization
      • Cross-validation
      • Hyperparameter tuning
      • Ensemble methods
      • Hard negative mining
      • ML Serving
        • Quantization
        • Kernel Auto-Tuning
        • NVIDIA TensorRT vs ONNX Runtime
    • Machine Learning Algorithms
      • Supervised Learning
        • Support Vector Machines
        • Adaptative boosting
        • Gradient boosting
        • Regression algorithms
          • Linear Regression
          • Lasso regression
          • Multi Layer Perceptron
        • Classification algorithms
          • Perceptron
          • Logistic Regression
          • Multilayer Perceptron
          • kNN
          • Naive Bayes
          • Decision Trees
          • Random Forest
          • Gradient Boosted Trees
      • Unsupervised learning
        • Clustering
          • Clustering metrics
          • kMeans
          • Gaussian Mixture Model
          • Hierarchical clustering
          • DBSCAN
      • Cameras
        • Intrinsic and extrinsic parameters
    • Computer Vision
      • Object Detection
        • Two-Stage detectors
          • Traditional Detection Models
          • R-CNN
          • Fast R-CNN
          • Faster R-CNN
        • One-Stage detectors
          • YOLO
          • YOLO v2
          • YOLO v3
          • YOLOX
        • Techniques
          • NMS
          • ROI Pooling
        • Metrics
          • Objectness Score
          • Coco Metrics
          • IoU
      • MOT
        • SORT
        • Deep SORT
  • Related Topics
    • Intro
    • Python
      • Global Interpreter Lock (GIL)
      • Mutability
      • AsyncIO
    • SQL
    • Combinatorics
    • Data Engineering Questions
    • Distributed computation
      • About threads & processes
      • REST vs gRPC
  • Algorithms & data structures
    • Array
      • Online Stock Span
      • Two Sum
      • Best time to by and sell stock
      • Rank word combination
      • Largest subarray with zero sum
    • Binary
      • Sum of Two Integers
    • Tree
      • Maximum Depth of Binary Tree
      • Same Tree
      • Invert/Flip Binary Tree
      • Binary Tree Paths
      • Binary Tree Maximum Path Sum
    • Matrix
      • Set Matrix Zeroes
    • Linked List
      • Reverse Linked List
      • Detect Cycle
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
    • String
      • Longest Substring Without Repeating Characters
      • Longest Repeating Character Replacement
      • Minimum Window Substring
    • Interval
    • Graph
    • Heap
    • Dynamic Programming
      • Fibonacci
      • Grid Traveler
      • Can Sum
      • How Sum
      • Best Sum
      • Can Construct
      • Count Construct
      • All Construct
      • Climbing Stairs
Powered by GitBook
On this page
  • Some concepts
  • Immutable Objects
  • Mutable Objects
  • Container objects
  • Mutable Default Arguments

Was this helpful?

  1. Related Topics
  2. Python

Mutability

PreviousGlobal Interpreter Lock (GIL)NextAsyncIO

Last updated 3 years ago

Was this helpful?

Some concepts

  • An object’s identity never changes once it has been created.

  • An object’s type defines the possible values and operations. It is unchangeable like the identity.

  • The value of some objects can change, depending on the type.

Some objects contain references to other objects, these objects are called containers (like tuple, list, or dictionary).

All variable names in Python are said to be references to the values.

Python keeps an internal counter on how many references an object has.

Once the counter goes to zero the GB in Python removes the object, thus freeing up the memory.

Immutable Objects

Every time when we try to update the value of an immutable object, a new object is created instead.

That’s when we have updated the first string it doesn’t change the value of the second. Immutable data types:

  • int

  • float

  • decimal

  • bool

  • string

  • tuple

  • range

a = "foo"
# the variable a points to the memory address 4000
# 4000 reference count is 1

a += "!"
# 1. the new content is stored in a different memory address
# 2. the reference points to the new memory adress 4016
# 3. 4016 has one reference and 4000 another
# 4. reference to 4000 is removed and count is 0
# 5. 4000 is ready to by free by the GC

Mutable Objects

  • list

  • dictionary

  • set

  • user-defined classes

Container objects

Some objects contain references to other objects, these objects are called containers (ie, tuple, list, or dictionary). The value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed.

However, the container is still considered immutable because when we talk about the mutability of a container only the identities of the contained objects are implied.

skills = ["Programming", "Machine Learning", "Statistics"]
person = (129392130, skills)
print(type(person))
> <class 'tuple'>

print(person)
> (129392130, ['Programming', 'Machine Learning', 'Statistics'])

skills[2] = "Maths"
print(person)
> (129392130, ['Programming', 'Machine Learning', 'Maths'])

Mutable Default Arguments

Related sources:

# Function declaration
def append_to(element, to=[]):
    to.append(element)
    return to
    
# Code execution
my_list = append_to(12)
print(my_list)

my_other_list = append_to(42)
print(my_other_list)

# Expected output
# > [12]
# > [42]

# Actual output
# > [12]
# > [12, 42]

# Solution
def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to

Python Basics: Mutable vs Immutable Objects
Common Gotchas (The Hitchhiker’s Guide to Python!)