-1

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;
}
Botje
  • 26,269
  • 3
  • 31
  • 41
cacarekt
  • 35
  • 6

3 Answers3

1

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)
DownloadPizza
  • 3,307
  • 1
  • 12
  • 27
0

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])
defladamouse
  • 567
  • 2
  • 13
  • yes this works but i didnt understand why works. Shouldnt be a local variable in function? – cacarekt Dec 09 '21 at 09:00
  • @cacarekt `a` indicates the _list_, not the _contents_ of the list. So when we say `a[0] = 20` we're changing the _contents_ of the list, but the list itself is unaffected. Specifically, `a` is a reference to the start of the list. We haven't changed where it starts, only what comes after. – defladamouse Dec 09 '21 at 09:04
  • Abusing a list for this will be incredibly bad for performance. This isnt C, lists arent fixed size and compiled away. Use a class instead – DownloadPizza Dec 10 '21 at 05:40
  • @DownloadPizza there was no indication of performance being a concern. This is simpler, a class is faster, which is better is entirely context dependent. – defladamouse Dec 10 '21 at 14:01
0

Not with an int as everyone has described. The "nicest" way depends on your goal but I just use a numpy array.

def modify(a):
    a += 10

x = np.array(10)
modify(x)
print(int(x))
Jono_R
  • 113
  • 2
  • 8