educative.io

Immutable data - python fundamental - https://www.educative.io/module/lesson/python-fundamentals-for-programmers/JYmYgLl0Mxg

“If we really need to update immutable variables through a function, we can simply assign the returning value from the function to the variable.”

Can anyone explain this statement above with examples and why so?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hi @Nitheshcr
Thanks for contacting the Educative Team. In the case of immutable data, the function can modify it, but the data will remain unchanged outside the function’s scope. Immutable objects are strings or numbers. The function cannot update the value of these objects until we update it outside the function scope by assigning the return value from the function to the variable.
For Example, if we change the value of an integer inside a function, original value will remain unchanged :

num = 20


def multiply_by_10(n):
    n *= 10
    num = n  # Changing the value inside the function
    print("Value of num inside function:", num)
    return n


multiply_by_10(num)
print("Value of num outside function:", num)  # The original value remains unchanged

image

But if we assign the return value of the function to variable, the original value will get changed.

num = 20


def multiply_by_10(n):
    n *= 10
    num = n  # Changing the value inside the function
    print("Value of num inside function:", num)
    return n


num= multiply_by_10(num)
print("Value of num outside function:", num)  # The original value remains unchanged

image

I hope it helps. Happy Learning :slight_smile: