Passing Objects as Parameters in Python
Variables containing objects (lists, sets, tuples, dictionaries) are passed by reference in functions. Let's rewrite the code in the function so that the first element of the variable being passed is changed to an exclamation mark. And below the function, we'll declare a variable whose value is a list:
pythondef func(tst):
tst[0] = '!'
print(tst)
lst = [1, 2, 3, 4, 5]
Since lists are passed by reference, when the function is called, the value of lst in the global scope will also change:
pythonfunc(lst) # ['!', 2, 3, 4, 5]
print(lst) # ['!', 2, 3, 4, 5]
Задание 1
What will be the result of running the following code:
pythondef func(lst):
lst[0] = '!'
lst = [1, 2, 3, 4, 5]
func(lst)
print(lst)
Задание 2
What will be the result of running the following code:
pythondef func(lst):
lst[0] = '!'
lst = [1, 2, 3, 4, 5]
lst = func(lst)
print(lst)
Задание 3
What will be the result of running the following code:
pythondef func(lst):
lst = '!'
lst = [1, 2, 3, 4, 5]
func(lst[0])
print(lst)
Задание 4
What will be the result of running the following code:
pythondef func(dct):
for key in dct.keys():
dct[key] += 2
dct = {
'a': 1,
'b': 2,
'c': 3,
}
func(dct)
print(dct)