Sets, tuples & sorting

Keep only what is unique

Lesson 9 of 20 · 8 min · Module 3: Working with collections

A set represents unique values. It is useful when duplicates are irrelevant, while a list remains useful when order and repetition matter.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Choose a collection by its purpose
  • Remove duplicates using a set
  • Make presentation order explicit

The idea

set(items) removes duplicates. Sets do not promise a useful presentation order. sorted(values) returns a new sorted list.

topics = ["loops", "lists", "loops"]
print(sorted(set(topics))) # ['lists', 'loops']

01Compare three collections

A list is an ordered, changeable sequence. A tuple is an ordered sequence that cannot be changed in place. A set keeps unique hashable values and is suited to membership and set operations.

02Separate uniqueness from ordering

Converting to a set answers “which distinct topics exist?” Sorting answers “how should we present them?” Keep those two decisions visible in the code.

Your turn

Define unique_topics(topics) to return an alphabetically sorted list of unique topic strings. Leave the input unchanged.

What the checks look for

  • Removes duplicates and sorts
  • Handles no topics
  • Accepts an immutable tuple
Try it in the editor →

Take this with you

Use the collection that matches the question you are asking.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →