Python Morsels Exercise

Set-like object that maintains insertion-order of items

3 bonuses 8 hints 15 solutions 257 users solved 23 reviews

I'd like you to make an OrderedSet class. This class should work like a set, but it should also maintain the insertion order of the items added to it (unlike Python's built-in set which is unordered).

>>> ordered_words = ['these', 'are', 'words', 'in', 'an', 'order']
>>> print(*set(ordered_words))
an words in these are order
>>> print(*OrderedSet(ordered_words))
these are words in an order
>>> print(*OrderedSet(['repeated', 'words', 'are', 'not', 'repeated']))
repeated words are not

This set should be relatively memory efficient and containment checks should be relatively time efficient:

>>> words = OrderedSet(['hello', 'hello', 'how', 'are', 'you'])
>>> len(words)
>>> 'hello' in words

Initially you don't have to worry about allowing sets to be modified after they've been made. Just focus on getting len and the in operator.

Bonus 1

This is just a preview of the problem statement.

This exercise includes 3 bonuses, 8 hint links, and automated tests.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python.

Python Morsels is design to help you improve your Python skills every week through 1 hour of deliberate practice.

Let me help you write more beautiful Python code. Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨