Python Forum
Pass by reference vs Pass by value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pass by reference vs Pass by value
#1
#What is the output?
val=100
print(val)
def changeVal():
    val=99
    print(val)
changeVal()
print(val)


#What is the output?
vals=[100,100,100]
print(vals)
def changeVals():
    vals[0]=99
    print(vals)
changeVals()
print(vals)
So I understand this as an example of pass by reference and pass by value.
The output is:

100
99
100
[100, 100, 100]
[99, 100, 100]
[99, 100, 100] #last line

1) Why isn't the last line [100,100,100]?
2) This is not a scope thing. Correct?
Reply
#2
Assignment never copies data.
There is a great youtube from PyCon 2015 that covers names and values.
Ned Batchelder PyCon 2015
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pass arguments from bat file to pyhon script from application absolut 2 901 Jan-13-2025, 11:05 AM
Last Post: DeaD_EyE
  Get an FFMpeg pass to subprocess.PIPE to treat list as text file? haihal 2 979 Nov-21-2024, 11:48 PM
Last Post: haihal
  how to pass a mongdb command to a module and execute it. cspower 0 838 Feb-03-2024, 09:54 PM
Last Post: cspower
  How to pass encrypted pass to pyodbc script tester_V 0 1,705 Jul-27-2023, 12:40 AM
Last Post: tester_V
  How to pass -Xutf8 parametri to python tierox 2 1,716 Jun-07-2023, 07:17 AM
Last Post: tierox
  Pass variable to subprocess paulo79 4 12,648 Apr-12-2022, 12:35 PM
Last Post: DeaD_EyE
  How to pass variables from one class to another hobbyist 18 19,578 Oct-01-2021, 05:54 PM
Last Post: deanhystad
Question How to pass a method as argument in an another method? anilanvesh 6 3,985 Sep-30-2021, 10:18 PM
Last Post: deanhystad
  How to pass list of values to a API request URL chetansaip99 0 4,309 Sep-28-2021, 07:37 AM
Last Post: chetansaip99
  Regex - Pass Flags as a function argument? muzikman 6 5,916 Sep-06-2021, 03:43 PM
Last Post: muzikman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020