assignment, references and list comprehension

J

Jim O'D

Hi everyone

Was just posting a question as I got confused with a big messy sheaf of
code when I thought I should make a simple example myself. Since I did I
thought I'd post it for the good of mankind.

I was confused as to whether the assignment of a result of a list
comprehension created references to the orginal objects... and it does
(at least for my self-defined object).

e.g.
initArrrgs = ["pick me","not me"]

class MyObject:
def __init__(arg):
self.argument = arg;

myObjects = [MyObject(initarg) for initarg in initArrrgs]
myObjects2 = [ob for ob in myObjects if ob.argument == "pick me"]

Then the following interrogation
>>> myObjects2[0].argument 'pick me'
>>> myObjects2[0].argument='juicy'
>>> myObjects2[0].argument 'juicy'
>>> myObjects[0].argument
'juicy'


Jim
 
F

Fredrik Lundh

Jim O'D said:
I was confused as to whether the assignment of a result of a list
comprehension created references to the orginal objects...

python never copies objects unless you tell it to, so the answer is yes. all
the "values" you pass around are object references, not binary blobs.
and it does (at least for my self-defined object).

trust me, it works the same way for all objects.

reading this may help:

http://effbot.org/zone/python-objects.htm

</F>
 
J

Jim O'D

trust me, it works the same way for all objects.

Yes, it was lack of trust that led me on a 2 hour re-write to avoid
creating subsets of object lists as I thought they were being copied. In
fact it was another error... huh.

I now know better.

Jim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,240
Messages
2,571,205
Members
47,844
Latest member
ChanceGris

Latest Threads

Top