Python Sets


Sets in Python are unordered collections of unique elements.

They are used to store multiple items in a single variable and can be very useful for tasks involving membership testing, removing duplicates, and set operations like union, intersection, and difference.

Properties of Sets

  1. Unordered - Sets do not maintain any order of elements. When you print a set, the items may appear in any order.
  2. Unique Elements - Sets automatically eliminate duplicate elements. Each element in a set must be unique.
  3. Mutable - You can add or remove items from a set.
  4. Iterable - You can iterate through the elements of a set using loops.


Creating Sets

You can create a set using curly braces {} or the set() function.

# Using curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)

# Using the set() function
another_set = set([1, 2, 3, 4, 5])
print(another_set)