0

Let's say I have a set of class C instances. Here is an example.

class C:
    pass

a = C()
a.distance = 1

b = C()
b.distance = 2

my_set = set()
my_set.add(a)
my_set.add(b)

I followed this post here, to sort the set of instances based on distance, but I noticed it can be a bit inefficient for my case. I am wondering if there is a more efficient way to perform the sort here?

new_set = sorted(my_set, key=lambda x: x.distance, reverse=True)
armin
  • 435
  • 1
  • 7
  • Using key `operator.attrgetter("distance")` might be slightly more efficient, but it will be cents on the dollar. Have you considered using a sorted container in the first place e.g. with [`bisect.insort`](https://docs.python.org/3/library/bisect.html#bisect.insort) or [`heapq.heappush`](https://docs.python.org/3/library/heapq.html#heapq.heappush)? – wim Jan 14 '22 at 05:14

0 Answers0