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:

Python
# List is a mutable type
a = [1, 2, 3]
b = a

print("Original a:", a)  # Original a: [1, 2, 3]
print("Original b:", b)  # Original b: [1, 2, 3]

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:

Python
# List is a mutable type
a = [1, 2, 3]
b = a

print("Original a:", a)  # Original a: [1, 2, 3]
print("Original b:", b)  # Original b: [1, 2, 3]

a[0] = 4

print(a)  # [4, 2, 3]
print(b)  # [4, 2, 3]

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.

Python
def cyclic_shift(x):
    x.insert(0, x.pop(-1))

a = [1, 2, 3]
cyclic_shift(a)
print(a)  # [3, 1, 2]

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

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal