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
#2
You could use
new_list = [copy.copy(x) for x in (a, b, a, b, a)]
Reply
#3
(Nov-12-2018, 08:36 PM)Gribouillis Wrote: You could use
new_list = [copy.copy(x) for x in (a, b, a, b, a)]

Thanks. That is definitely cleaner so +1 for that. Is the copy module the only way to achieve this? I noticed that lists have a .copy() method which does a shallow copy.
Reply
#4
(Nov-12-2018, 08:39 PM)CanadaGuy Wrote: Is the copy module the only way to achieve this?
In practice, there are often other ways to create new instances, it all depends on the class. I noticed in my own code that I almost never use the copy module. For example in order to copy a dict D, one usually writes new = dict(D).
Reply
#5
Thanks, I'll look into those alternative methods. These are custom classes, so I suppose if I wanted something more elegant, I could code something myself. Good to know there are alternatives.
Reply


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,546 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Mathplotlib - passing reference to axs to function qmfoam 5 2,946 Aug-17-2020, 09:02 PM
Last Post: qmfoam
  Passing an argument by reference Exsul 12 4,698 Aug-22-2019, 07:29 AM
Last Post: DeaD_EyE
  Passing a list by reference virgik89 6 4,502 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