Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • add this to example, t = [3, 2, 1, 1, 2, 5, 6, 7, 8], shows the difference clearly! Commented Oct 26, 2019 at 4:44
  • 3
    "...overhead of creating a dictionary first... If you don’t actually need to preserve the order, you’re better off using a set." — I profiled this because I was curious if it was actually true. My timings show that indeed the set is slightly faster: 1.12 µs per loop (set) vs 1.53 µs per loop (dict) over 1M loops with an absolute time difference of about 4s over 1M iterations. So if you're doing this in a tight inner loop you may care, otherwise probably not. Commented Dec 9, 2019 at 13:30
  • @millerdev I was going to say something like “overhead does not only mean timing” but then I checked and it appears that a keyed dictionary is actually smaller in memory than a set with the same elements. At least in current versions of Python. That’s really surprising – but yes, it’s a good point! Thanks! Commented Dec 9, 2019 at 15:05
  • 4
    This solves the issue with unhashable types (where t is a list of dicts): [dict(d) for d in set([frozenset(i.items()) for i in t])] Commented Dec 11, 2019 at 7:52
  • 1
    @BigDreamz dict.fromkeys() creates a dictionary in linear time, and list() will create a list from it also in linear time. Commented Aug 25, 2020 at 6:16