Nov-12-2018, 07:57 PM
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:
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?
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.
1 2 3 4 5 6 7 8 9 10 11 |
a = objectA b = objectB new_list = [ a, b, a, b, a] print (new_list) |
1 2 3 4 5 6 7 8 9 10 11 12 |
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) |
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.