🔍

Differences Between Value and Reference Types

Oct 25, 2024

Understanding Value Types and Reference Types in Python

Value Types

  • Examples: int, float, bool
  • Passing by Value:
    • When a value type is passed as an argument to a function, a copy of the value is made.
    • Any changes made to the copy inside the function do not affect the original variable outside the function.
    • Example:
      • A variable a is initialized with the value 2.
      • The function add_five is called with a as the argument.
      • Inside add_five, the parameter x is modified by adding 5, resulting in 7.
      • When the function returns, the original variable a remains unchanged with the value 2.

Reference Types

  • Examples: Arrays, Lists
  • Passing by Reference:
    • When a reference type is passed to a function, a reference to the original value is passed, not a copy.
    • Changes made to the elements inside the reference type persist after the function returns.
    • Example:
      • A list b is initialized with a single element 2 at index 0.
      • The function change is called with b as the argument.
      • Inside change, the 0 index of the list x is modified to 10.
      • When the function returns, the original list b reflects this change, now containing 10 at index 0.

Examples Recap

  • Value Type Example: add_five Function
    • a is initialized to 2.
    • add_five(a) is called, modifying x to 7 inside the function.
    • After the function returns, a is still 2.
  • Reference Type Example: change Function
    • b is initialized as [2].
    • change(b) is called, and x[0] is changed to 10 inside the function.
    • After the function returns, b is [10].

Key Takeaways

  • Value types are immutable when passed to functions; changes don't affect the original.
  • Reference types are mutable when passed to functions; changes affect the original.