Understanding Python Argument Passing

Oct 25, 2024

Lecture Notes on Python Argument Passing

Value Types

  • Examples: int, float, bool
  • Passing by Value:
    • When a value type is passed to a function, a copy is made.
    • Changes made to the parameter inside the function do not affect the original variable.
    • Example:
      • Local variable a is passed as parameter x.
      • Changes to x inside the function don't change a.
      • After function execution, a retains its original value.

Reference Types

  • Examples: arrays, lists
  • Passing by Reference:
    • A reference to the original value is passed to the function.
    • Changes made to the parameter inside the function persist after the function returns.
    • Example:
      • A list is created and passed to a function.
      • Both external variable and parameter within function point to the same list.
      • Changes to the list inside the function affect the original list.

Detailed Examples

Example 1: Value Type

  • Variable a is initialized to 2.
  • add5 function is called:
    • Inside add5, x is modified by adding 5.
    • Prints x, which shows 7 (inside function scope).
  • After add5 returns, printing a shows it is still 2.

Example 2: Reference Type

  • List b is created with [2] at index 0.
  • change function is called:
    • Inside change, the list element at index 0 is modified to 10.
    • Prints list showing [10] (inside function scope).
  • After change returns, printing b shows [10].

Conclusion

  • Understanding the difference between value and reference types is crucial in Python.
  • Helps predict how data will transform within functions.