Most efficient way to update attribute of one instance

Posted by Begbie00 on Stack Overflow See other posts from Stack Overflow or by Begbie00
Published on 2010-05-24T04:28:48Z Indexed on 2010/05/24 4:30 UTC
Read the original article Hit count: 242

Hi all -

I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this?

Right now, I'm doing the following:
1) Manage the instances in a list.
2) Iterate through the list to find a key value.
3) Once I find the right object within the list (i.e. key value = value I'm looking for), change whatever attribute I need to change.

for Instance within ListofInstances:
    if Instance.KeyValue == SearchValue:
        Instance.AttributeToChange = 10

This feels really inefficient: I'm basically iterating over the entire list of instances, even through I only need to change an attribute in one of them.

Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?) Is a dictionary any more efficient in this case? Should I be using something else?

Thanks,
Mike

© Stack Overflow or respective owner

Related posts about python

Related posts about oop