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 a mongdb command to a module and execute it. cspower 0 275 Feb-03-2024, 09:54 PM
Last Post: cspower
  How to pass encrypted pass to pyodbc script tester_V 0 800 Jul-27-2023, 12:40 AM
Last Post: tester_V
  How to pass -Xutf8 parametri to python tierox 2 822 Jun-07-2023, 07:17 AM
Last Post: tierox
  Pass variable to subprocess paulo79 4 9,953 Apr-12-2022, 12:35 PM
Last Post: DeaD_EyE
  How to pass variables from one class to another hobbyist 18 10,376 Oct-01-2021, 05:54 PM
Last Post: deanhystad
Question How to pass a method as argument in an another method? anilanvesh 6 2,663 Sep-30-2021, 10:18 PM
Last Post: deanhystad
  How to pass list of values to a API request URL chetansaip99 0 3,473 Sep-28-2021, 07:37 AM
Last Post: chetansaip99
  Regex - Pass Flags as a function argument? muzikman 6 3,482 Sep-06-2021, 03:43 PM
Last Post: muzikman
Exclamation win32com: How to pass a reference object into a COM server class Alfalfa 3 4,799 Jul-26-2021, 06:25 PM
Last Post: Alfalfa
  Filtering characters that pass through serial xbit 0 1,371 May-06-2021, 11:56 PM
Last Post: xbit

Forum Jump:

User Panel Messages

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