Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Python
About Lesson

In Python, the set() function is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove elements after creation, but they do not allow duplicates, and they don’t maintain any specific order of elements.

Syntax: set(iterable)

  • iterable: This can be any iterable object like a list, tuple, string, or dictionary (its keys are used to form the set).

Key Features of Sets:

  1. Uniqueness: A set automatically removes duplicate elements.
  2. Unordered: The elements in a set are not indexed and do not maintain any particular order.
  3. Mutable: You can add or remove elements from a set after its creation.

Example 1: Creating a Set

Python
# Using set() with a list
my_set = set([1, 2, 3, 4, 4, 5])
print(my_set)  # Output: {1, 2, 3, 4, 5}

# Using set() with a string
my_set = set("hello")
print(my_set)  # Output: {'h', 'e', 'l', 'o'}

Example 2: Adding and Removing Elements

Python
# Create a set
my_set = {1, 2, 3}

# Add an element to the set
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}

# Remove an element from the set
my_set.remove(2)
print(my_set)  # Output: {1, 3, 4}

Example 3: Set Operations

Python
# Set A
set_a = {1, 2, 3}

# Set B
set_b = {3, 4, 5}

# Union of sets
union_set = set_a | set_b
print(union_set)  # Output: {1, 2, 3, 4, 5}

# Intersection of sets
intersection_set = set_a & set_b
print(intersection_set)  # Output: {3}

# Difference of sets
difference_set = set_a - set_b
print(difference_set)  # Output: {1, 2}

Common Methods:

  • add(elem): Adds an element to the set (if not already present).
  • remove(elem): Removes an element from the set. Raises a KeyError if the element is not present.
  • discard(elem): Removes an element from the set, but does not raise an error if the element is not present.
  • clear(): Removes all elements from the set.
  • pop(): Removes and returns an arbitrary element from the set.
  • copy(): Returns a shallow copy of the set.