Mutable vs. Immutable Arguments

Parameter Passing in Functions

  • When a function is called, the current values of the arguments passed become the initial values of their corresponding formal parameters.

Passing Variables as Arguments

  • When variables are passed, changes to formal parameters in the function may or may not affect the actual arguments.

Example: No Side Effects on Immutable Types

  • Immutable Types: Integers, floats, Booleans, strings, tuples.
  • Changes to formal parameters do not affect the actual arguments
age = 30
def birthday(a):
    a = a + 1  # Changes only the local variable a
birthday(age)
print(age)  # Outputs: 30 (unchanged)

Example: Side Effects on Mutable Types

  • Mutable Types: Lists, dictionaries, sets.
  • Changes to formal parameters affect the actual arguments.python
scores = [10, 20, 30]
def add_bonus(lst):
    lst[0] = lst[0] + 5  # Changes the actual list
add_bonus(scores)
print(scores)  # Outputs: [15, 20, 30]
Design a site like this with WordPress.com
Get started