Python Forum

Full Version: Passing by reference or value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
You could use
new_list = [copy.copy(x) for x in (a, b, a, b, a)]
(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.
(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).
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.