Home > Enterprise >  Can i modify variable in function without return in python like using pointers in c
Can i modify variable in function without return in python like using pointers in c

Time:12-09

i just wanna make learn how can i write this c code in python ?

#include <iostream>

void modify(int* a){
    *a = 20;
}

int main(){

    int x = 10;
    modify(&x);
    std::cout << x;
    // OUTPUT: 20
    return 0;
}

CodePudding user response:

This can not work for integers because integers in python are completely immutable. You can not change an integer in python. When you do for example a = 1, you create a new int with the value a 1 and bind the variable a to it. Now, the easiest way to do this would be to have some reference type, like a class.

class IntRef:
  def __init__(self, a):
    self.a = a

def modify(some):
  some.a = 20

ir = IntRef(10)
modify(ir)
print(ir)

CodePudding user response:

The simple answer is "you can't". But, if you had a use case where equivalent behaviour was required, the easiest way would be to wrap your variable into a mutable type. I would do the following:

def modify(a):
    a[0] = 20

x = [10]
modify(x)
print(x[0])
  • Related