1

This snippet of python code

def changeValue(x):                                                                          
     x = 2*x                                                                                  
                                                                                              
 a = [1]                                                                                      
                                                                                              
 changeValue(a[0])                                                                            
                                                                                              
 print(a[0])    

Will print the result "1" when I would like it to print the result "2". Can this be done by only altering the function and no other part of the code? I know there are solutions like

def changeValue(x):
    x[0] = 2*x[0]

a = [1]

changeValue(a)

or

def changeValue(x):
    return 2*x

a = [1]

a[0] = changeValue(a[0])

I am wondering if the argument passed as-is can be treated as a pointer in some sense.

[edit] - Just found a relevant question here so this is likely a duplicate that can be closed.

DJames
  • 571
  • 3
  • 17

1 Answers1

0

No it's not possible. If you pass a[0], it's an int and it can't be mutated in any way.

If the int was directly in the global namespace, you could use global keyword. But it's not. So again no.

S.B
  • 13,077
  • 10
  • 22
  • 49