Python. Arguments in functions. Passing arguments to a function. Changing arguments in the body of a function

Arguments in functions. Passing arguments to a function. Changing arguments in the body of a function


Contents


Search other websites:




 1. How are arguments passed to a function? The operation of the mechanism for passing an argument to a function

Arguments can be passed to the function. Arguments are mutable or immutable objects. In Python, it matters which category of objects (mutable or immutable) an argument belongs to.

For example, mutable objects include lists and dictionaries. Immutable objects include numbers, strings, tuples. Immutable objects include numbers, strings, tuples.

If an immutable object is passed to a function, then this object is passed “by value”. This means that changing this object inside the function will not change it in the calling code.

If a variable object is passed to a function, then this object is passed by “pointer”. Changing such an object within a function will affect that object in the calling code.

 

2. Examples of passing immutable objects to a function
2.1. Passing a number to a function

In the example, for demonstration purposes, the Mult2() function is implemented, which receives a number as a parameter. This number is doubled in the body of the function. The result is displayed.

# Passing a number to a function
# A number is an immutable object, so it is passed "by value"

# Declare a function that takes some number and multiplies it by 2
def Mult2(number):
    # multiply number by 2
    number = number*2

    # print the value of the number in function
    print("Mult2.number = ", number)

# Using of function
num = 25 # some number
Mult2(num) # invoke the function

# print the number num after calling the function
print("num = ", num) # num = 25 - the number has not changed

After starting the program will give the following result

Mult2.number =   50
num = 25

As you can see from the result, in the function, the value of the number num is multiplied by 2 and is 50. However, this result is not passed to the calling code, here the num value remains 25 as before the function call. This confirms the passing “by value” of an immutable object, which is a number.

 

2.2. Passing a string to a function

The operation of the ReverseStr() function, which reverses the string received by the parameter, is demostrated.

# Passing a string to a function
# A string is an immutable object, so it is passed "by value"

# Declare a function that receives a string,
# reverse it and display it
def ReverseStr(text):
    # reverse a string
    txt = ''

    # the loop of string processing
    for c in text:
        txt = c + txt

    text = txt

    # display the reversed text
    print('ReveseStr.text = ', text)

# Invoke the ReverseStr() function
Text = "Hello world!"
ReverseStr(Text)
print("Text = ", Text)

The result of the program is as follows

ReveseStr.text =   !dlrow olleH
Text = Hello world!

As you can see from the result, the string in the body of the function is changed (reversed). Since a copy of the string is passed to the function, only this copy is changed in the function body. The original that was passed to the function is not changed when the function is called.

 

2.3. Passing a tuple to a function

 

# Passing a tuple to a function
# A function that takes a tuple as a parameter
def PassTuple(T):
    # Change the tuple
    T = ([1,2], 'a', 25.88)
    print('PassTuple.T = ', T)

# Create a tuple
TT = ( [2, 3.5], True, 'abcd')

# Call the function and pass a TT tuple to it
PassTuple(TT)

# Print the tuple TT
print('TT = ', TT)

The result of the program

PassTuple.T = ([1, 2], 'a', 25.88)
TT = ([2, 3.5], True, 'abcd')

Just as in the previous two examples, passing a tuple to a function is by value.

 

3. Examples of passing mutable objects to a function
3.1. Passing a list to a function

A function that takes a list as a parameter is demonstrated. Then, in the body of the function, this list is changed (the first and second elements of the list are changed).

# Passing a list to a function. List is a mutable object
# A function that takes a list as a parameter
def ChangeList(L):
    # Change the list
    L[0] = 777 # Change the first item of list
    L[1] = (2, 3) # Change the second item of list

    # Print list in the function
    print('ChangeList.L = ', L)

# Create a list
LL = [ [2, 3.5], True, 'abcd' ]

# Print the list LL for control
print('LL = ', LL)

# Call the function and pass the LL list to it
ChangeList(LL)

# Print the LL list after the function call
print('LL = ', LL)

The result of the program

LL = [[2, 3.5], True, 'abcd']
ChangeList.L =   [777, (2, 3), 'abcd']
LL = [777, (2, 3), 'abcd']

As you can see from the result, changing the list in the body of the function changes this list in the calling code. This means that the list is passed as a C pointer.

 

3.2. Passing a dictionary to a function

Demonstrates the ChangeDict() function, which takes a dictionary as a parameter. In the body of the function, the individual elements of the dictionary are changed that are placed at positions numbered 0 and 2.

# Passing a dictionary to a function. Dictionary - mutable object
# A function that takes a dictionary as a parameter
def ChangeDict(D):
    # Change dictionary
    D['A'] = 100 # Change the first element of the list
    D['C'] = 300 # Change the third element of the list

    # Print the list in the function
    print('ChangeDict.D = ', D)

# Create a dictionary
DD = { 'A':5, 'B':10, 'C':20 }

# Print DD dictionary for control
print('DD = ', DD)

# Call the function and pass the DD dictionary to it
ChangeDict(DD)

# Print the list DD after calling the function
print('DD = ', DD)

The result of the program

DD = {'A': 5, 'B': 10, 'C': 20}
ChangeDict.D =   {'A': 100, 'B': 10, 'C': 300}
DD = {'A': 100, 'B': 10, 'C': 300}

 

4. Ways to avoid changing objects arguments in the calling code

In cases where you need to prohibit changing the list object inside a function, you can use the methods described below.

Method 1. When passing a list to a function, you can convert this list to a tuple using the tuple() operation. After that, it will not be possible to change the list in the function body.

The following code demonstrates how to use the tuple() operation to convert a list to a tuple.

# Passing a list to a function with converting to a tuple
def PassList(L):
    # Trying to modify the list
    L[0] = 100 # Error!

    # Print the list in the function
    print('PassList.L = ', L)

# Create a list
LL = [ 1, 3, 8, 10 ]

# Call the function and pass it the LL list, which is converted to a tuple
PassList(tuple(LL))

# Display the list L after the function call
print('LL = ', LL)

The LL list is passed to the PassList() function as a tuple

PassList(tuple(LL))

After that, it will not be possible to change the LL element in the PassList() function. If you run the program, an exception will be generated with the message

TypeError: 'tuple' object does not support item assignment

Method 2. When passing a list to a function, you can use the slice operation [:] as shown in the following program

# Passing a list to a function with the converting to a slice
def PassList(L):
    # Trying to modify the list
    L[0] = 100 # Error!

    # Print the list in the body of function
    print('PassList.L = ', L)

# Create a list
LL = [ 1, 3, 8, 10 ]

# Call the function and pass the list to it as a slice [:]
PassList(LL[:])

# Display the list L after the function call
print('LL = ', LL)

In the above code, when calling a function using the string

...

PassList(LL[:])

...

slice LL[:] makes a copy of the list. This way, changes to the list inside the function will not change the list in the calling code, since those changes will be performed on the copy.

After running for execution, the program will give the following result

PassList.L = [100, 3, 8, 10]
LL = [1, 3, 8, 10]

 

5. Features of passing arguments to a function. Results

For the arguments that are passed to the function, the following features can be distinguished:

1. If a function is called from external code with an argument passed to it, then in the body of the function this argument (object) is automatically assigned to the corresponding local variable of the function.

For example. The automatic assignment of an argument value to a local variable of a function is demonstrated.

# Arguments.
# Passing an argument to a function

# A function that takes an argument and displays it on the screen
def Argument(v):
    print('Argument.v = ', v)
    return

# Demonstration of implicit assignment
value = 'Hello world!' # some object

# pass object value to the function Argument(),
# implicit assignment occurs Argument.v = value
Argument(value) # Argument.v = Hello world!

2. Function arguments are object references. When passing an argument, an object reference is passed to the function. The passed references are implemented as pointers in C. Since, when passing an argument to the function, the object reference is copied, the object itself is never copied. In other words, an automatic copy of an object is not created when it is passed to a function, only a copy of the reference is made.

3. If you assign a value to the name of the passed parameter in the body of the function, this will not affect the value of the external argument in the calling code. This is because the names of the arguments in the calling code become new names in the function’s scope.

For example. In the example, the Func() function changes the value of the D parameter to 25. In the calling code passed an argument with the same name D with the value 30. However, after calling the function from the calling code, the value of the external argument D did not change, which had to be proven.

# Arguments.
# Passing an argument to a function - no copy of the object is made

# A function that receives an argument-list
def Func(D):
    D = 25 # here D is the new name
    print('Func.D = ', D)

D = 30
Func(D) # invoke the function
print('D = ', D) # D = 30 - the value of the object in the function has not changed

4. If an argument (object) is passed to the function, which is mutable (list, dictionary), then changing this argument inside the function will change the argument in the calling code. This only applies to changes to the constituent elements of an object (single element of a dictionary or list). If you try to change an object by its common name (using the assignment operator =), then there will be no changes in the calling code (a reference to the object is passed, namely, the reference cannot be changed).

For example. The following example declares two functions that attempt to modify an input parameter (list) by its name:

  • the ChangeList() function – tries to change the list by reference name L. This change does not affect the external LL passed from the calling code. This is due to the fact that a copy of the reference is made, changes to the copy do not change the original;
  • the ChangeList2() function – tries to change a list item by reference name L and item position. Result – The change affects the external LL in the calling code. This is because the copy and the original point to the same data (the same area of memory).

 

# Arguments.
# Passing a mutable object as an argument

# A function that takes a list parameter and modifies the entire list
def ChangeList(L):
    # Change the list in the function by name
    L = [ 1, 2, 3] # does not affect external code

    # Print the modified list
    print('ChangeList.L = ', L) # ChangeList.L = [1, 2, 3]

# A function that takes a list parameter and modifies a list item
def ChangeList2(L):
    # Change an integral element of the list
    L[1] = 'abcd' # affects external code
    print('ChangeList2.L = ', L)

# ----- The calling code of the module-------
LL = [ 'a', 'b', 'c' ] # a list

# 1. Passing a list to the ChangeList() function and displaying it
ChangeList(LL) # pass list to function
print('LL = ', LL) # LL = ['а', 'b', 'с'] - the list has not changed

# 2. Pass list LL to the function ChangeList2()
ChangeList2(LL)
print('LL = ', LL) # LL = ['a', 'abcd', 'c' ] - the list has not changed

After execution, the program will give the following result

ChangeList.L = [1, 2, 3]
LL = ['a', 'b', 'c']
ChangeList2.L =   ['a', 'abcd', 'c']
LL = ['a', 'abcd', 'c']

 


Related topics