Home Tutorials Python Tutorial Sets
Sets

Sets


Definition: A set is an unordered collection of items where every element is unique (no duplicates are allowed). Sets are written with curly brackets.

Why: Sets are included among the main collection types because they are highly efficient for operations where you need to ensure there are no duplicate entries (such as a list of unique visitor IDs) and for mathematical operations like unions and intersections.

Syntax

set_name = {item1, item2, item3}

Example

numbers = {1, 2, 3, 3, 4}
print(numbers)

Explanation

  • Curly Brackets: Sets are defined using curly brackets { }.
  • Automatic Deduplication: Even though the number 3 was added twice in the example, when Python prints the set, it will only display {1, 2, 3, 4}. Duplicate items are automatically removed.

Key Notes

  • Sets are unordered, meaning the items do not have a defined order and can appear in a different order every time you print them. Because of this, you cannot access items by an index number (e.g., numbers[0] will cause an error).
  • Set items are unchangeable (immutable) once added, but you can add new items or remove existing ones using methods like .add() and .remove().
Example

🏋️ Test Yourself With Exercises

Take our quiz on Sets to test your knowledge.

Exercise »