2

I have a list of class objects who have two values, x and y. This is my current code to grab an individual object from the list:

for object in object_list:
    if object.x == 10 and object.y == 10:
        current_object = object
        break

And then I can do operations on the object by referencing current_object. However, my problem is that the list contains 2000 class object entries, and I worry that it will be very inefficient to iterate through the list like that until I find the desired object.

Is there a more efficient way for me to get my requested object?

3
  • Have you considered using dictionaries ? Can it answer your needs ? Commented Jun 23, 2015 at 23:10
  • Use dictionaries, whose key is the pair (tuple) x and y of each corresponding object. Since dictionaries have a better time complexity for searching than lists... Commented Jun 23, 2015 at 23:11
  • Consider this another vote for a dict; specifically, mapping {(foo.x, foo.y): foo, ...}. Also, don't name your own objects object... Commented Jun 23, 2015 at 23:11

1 Answer 1

3

If you are going to do the lookup again and again, then you can turn your list to a dictionary, like this

lookup = {(obj.x, obj.y): object for obj in object_list}

This will create a dictionary with keys as the tuples of x and y values from objects.

Now, you can simply do the lookup like this

lookup[(x_value, y_value)]

or if you want to return a default value if the key is not found in the dictionary, then you can use the dictionary.get, like this

lookup.get((x_value, y_value), None)

This will not throw a KeyError, if the key is not found in the dictionary, but return None.

Is there a more efficient way for me to get my requested object?

The above suggested dictionary method will be very fast, because the dictionary lookup can happen in constant time (as they internally use hash tables), but searching the list will be in linear time complexity (we need to iterate the list and check elements one by one).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.