Mutable Types: Lists
When a list is passed between variables, both references point to the same memory location. This means that a change made through one reference is reflected in all others. Consider the following example:ages and ages2 refer to the same list. Modifying an element via one variable affects the shared object, as demonstrated by the output.
Immutable Types: Scalars
Immutable scalar values such as numbers and strings behave differently. When passed as parameters to functions, they are copied locally, so modifications do not affect the original variable. For example, consider the following code:multiply function, if you check the value of age, it remains 22 because the function only modifies a local copy of the variable.
Lists as Function Parameters
Let’s look at another example that demonstrates how mutable objects like lists behave when passed as function parameters. In this example, a function modifies the first element of a list:nums is a mutable object, the change made inside the function affects the original list. This example reinforces the fact that mutable objects are passed by reference, and modifications within a function impact the original data.
Understanding the distinction between mutable and immutable data types is essential for writing predictable and bug-free code. Always consider whether a function should alter the original object or work with a copy to avoid unintended side effects.
Summary
- Mutable Objects (Lists): Passed by reference. Changes within functions will modify the original object.
- Immutable Objects (Scalars): Passed by value. Functions work with a copy, leaving the original variable unchanged.