• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • Python
  • Ubuntu
  • Maven
  • Archived
  • About
Python | Sets
A set is a collection of unordered unique, immutable (hashable) items.
Sets are mutable; which means you can add or remove items.
Items in the set need to be of hashable types (integers, strings, tuples with immutable items).
Mixed hashable types can be added to the same set.
Duplicate items are automatically removed.

Creating basic sets:
Use curly braces ({}) to create a set.
Use commas to separate items in the set.

Sets with one item:

Empty sets:

Important: empty curly braces ({}) create an empty dictionary, not a set:

Hashable elements:
You get a TypeError if you use an unhashable element to declare a set:

Using tuples, strings, numbers, immutable sets should work fine:

Creating sets from lists:

Creating sets from strings:

Creating sets from tuples:

Set comprehensions:

Set access and iteration:
Sets do not support indexing because they are unordered:

To access items in a set, iterate over it using a loop or convert it to a list:

Common set operations:
  • Adding elements:

  • Removing elements:

  • Union: x | y (elements in x or y)

  • Intersection: x & y (elements in x and y)

  • Difference: x - y (elements in x but not in y)

  • Symmetric difference: x ^ y (elements in either x or y, but not both)

  • Membership: i in x (check if i in x)

© 2025  mtitek