Python Forum
Passing by reference or value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing by reference or value
#1
Being new to Python, I figured I was bound to run into something like this. I'm used to programming where values are passed around, and I had to go to great lengths to operate on references. Now in Python it seems to be the reverse. I wanted to make sure I'm not overlooking something in this fairly simple example:

a = objectA
b = objectB

new_list = [
    a,
    b,
    a,
    b,
    a]

print(new_list)
If I execute this code, (I think) I will get a list of the addresses of each object. In Python, this would produce a result where all the 'a' objects would be at one address, and all the 'b' objects would be at another. Is it the (only) way that if I want new instances of the a and b objects, I need to use something like the following instead?

import copy
a = objectA
b = objectB

new_list = [
    copy.copy(a),
    copy.copy(b),
    copy.copy(a),
    copy.copy(b),
    copy.copy(a)]

print(new_list)
I learned of the idea from a few StackOverflow posts for lists, as well as the official Python docs:
https://docs.python.org/3/library/copy.html

I just want to make sure I haven't overlooked any other ways that are either easier or more straightforward.
Reply


Messages In This Thread
Passing by reference or value - by CanadaGuy - Nov-12-2018, 07:57 PM
RE: Passing by reference or value - by Gribouillis - Nov-12-2018, 08:36 PM
RE: Passing by reference or value - by CanadaGuy - Nov-12-2018, 08:39 PM
RE: Passing by reference or value - by Gribouillis - Nov-12-2018, 08:42 PM
RE: Passing by reference or value - by CanadaGuy - Nov-12-2018, 08:44 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,611 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Mathplotlib - passing reference to axs to function qmfoam 5 3,039 Aug-17-2020, 09:02 PM
Last Post: qmfoam
  Passing an argument by reference Exsul 12 4,853 Aug-22-2019, 07:29 AM
Last Post: DeaD_EyE
  Passing a list by reference virgik89 6 4,633 Jul-01-2018, 04:26 PM
Last Post: virgik89

Forum Jump:

User Panel Messages

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