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
  How to pass variables from one class to another hobbyist 18 827 Oct-01-2021, 05:54 PM
Last Post: deanhystad
Question How to pass a method as argument in an another method? anilanvesh 6 285 Sep-30-2021, 10:18 PM
Last Post: deanhystad
  How to pass list of values to a API request URL chetansaip99 0 453 Sep-28-2021, 07:37 AM
Last Post: chetansaip99
  Regex - Pass Flags as a function argument? muzikman 6 429 Sep-06-2021, 03:43 PM
Last Post: muzikman
Exclamation win32com: How to pass a reference object into a COM server class Alfalfa 3 672 Jul-26-2021, 06:25 PM
Last Post: Alfalfa
  Filtering characters that pass through serial xbit 0 444 May-06-2021, 11:56 PM
Last Post: xbit
  How can I pass&return ndarray between python and c++? JESuh 0 487 Mar-09-2021, 08:29 AM
Last Post: JESuh
  Possible to dynamically pass arguments to a function? grimm1111 2 672 Feb-21-2021, 05:57 AM
Last Post: deanhystad
  Why Pass Functions as arguments? muzikman 14 1,860 Jan-18-2021, 12:08 PM
Last Post: Serafim
  How do I pass a dictionary for the in3_registry value for the Incubed Python API? nilesh 0 455 Jan-11-2021, 11:19 AM
Last Post: nilesh

Forum Jump:

User Panel Messages

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