Modifying Variables with Functions in Python
Lesson Introduction
Welcome to the lesson on modifying variables with functions in Python! Understanding how functions can modify variables is crucial for complex programs. By the end of this lesson, you will comprehend how passing variables to functions can affect your code, specifically how lists and other mutable types can be modified.
Modifying Lists
In Python, data types are categorized into mutable and immutable types. This is important when passing variables to functions. Mutable types include lists, dictionaries, and sets, while immutable types include integers, strings, and tuples.
It is important to understand how copying works in Python. Take a look at this example:
The a variable stores a reference to the list. When a is copied to b, the list is not copied – only the reference is. Both a and b reference the same list in this example. Modifying a will also modify b and vice versa:
Here, we only modified a, but as b is the reference to the same list, it is also modified.
Example of Modifying a List with a Function
It is most important when working with functions. Python's mutable and immutable types show different behaviors when passed to functions.
For mutable types like lists, the reference to the original data is passed. Changes made to the parameter in the function reflect in the original variable.
For immutable types like integers, only a copy of the value is passed to the function. Changes made do not affect the original variable.
Let's use the cyclic_shift function to see how we can modify lists within a function.
Since lists are mutable, x references the same list as a does, the cyclic_shift function modifies the original a list directly. This applies to dictionaries and sets as well, as they are mutable types.
Pass-By-Reference vs. Pass-By-Value
