0

I'm using a dict to ensure that I have only one copy of a Path in my system:

 for obj in obj_list:
     obj_dict[obj.fullname]=obj

Is there some more efficient way to do this that I'm missing?

Ray Salemi
  • 5,247
  • 4
  • 30
  • 63

3 Answers3

2

Not really. This method will be slower than a linear search for smaller data sets, but will be much faster for larger data sets as testing for a duplicate entry is a hash table lookup.

The time complexity of your code is amortized O(n) (the best you can hope to achieve when you have to process every item in a data set), while doing a linear search is O(n2).

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

Try obj in obj_list

like this 'a' in x

https://www.tutorialspoint.com/python/membership_operators_example.htm

Bruno Mazzardo
  • 1,586
  • 1
  • 15
  • 27
  • 2
    This will perform a linear search, which has `O(n)` time. OP's code has `O(1)` time for testing for the presence of an item. – cdhowie May 17 '18 at 17:00
0

look at create-a-dictionary-with-list-comprehension-in-python

List comprehension is much faster - I assume this is meant by efficency.

Ray Salemi
  • 5,247
  • 4
  • 30
  • 63
Andreas
  • 11
  • 1
  • 3
  • List comprehension will be less code but not faster. It has higher memory complexity as it needs to hold an extra copy of the entire data set in memory. With a sufficiently large data set, this will result in unnecessary swapping. – cdhowie May 17 '18 at 17:10
  • Also, I'm not certain how to apply it in this case. It seems to expect a list of tuples. – Ray Salemi May 17 '18 at 17:12
  • list comprehension perform better here because you don’t need to load the append attribute of the list and call it as a function! I do not get the thing with the swapping? We are purely in memory. – Andreas May 17 '18 at 17:20