+ 1

How do i pass by reference?

def func(x,y): x = y x = 10 print(x) func(x,20) print(x) Outputs = 10 10 How do i make it so that value of x is changed to 20?

6th Dec 2019, 8:48 AM
a;lskdjfhg
a;lskdjfhg - avatar
3 ответов
+ 3
You cannot pass integer values as references, it is not like in C or C++. The difference is that in Python either the type of variable is a reference by itself or you simply pass the value. For instance, if you pass an object like a list, you can change what's inside it. Thus, the only way I see for you is, for example, to create a list with the x value inside, and then pass it. The value inside the list will change. def func(x: list, y): if len(x) > 0: x[0] = y x = [10] print(x[0]) # it prints 10 func(x, 20) print(x[0]) # it prints 20 Hope that helps!
6th Dec 2019, 9:07 AM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
+ 3
Here is a very good part of a python tutorial. It's not up to date regarding the python version (print is without ()), but anyway it gives a good view on how parameters and arguments work in python. Also other parts of the tutorial are worth taking a look at. https://www.python-course.eu/passing_arguments.php
6th Dec 2019, 10:16 AM
Lothar
Lothar - avatar
+ 1
thx
6th Dec 2019, 9:37 AM
a;lskdjfhg
a;lskdjfhg - avatar