DEV Community

Punitha
Punitha

Posted on

Python Set

What is a Set?

A Set is a collection of values in Python that:

  • Stores unique elements
  • Does not allow duplicate values
  • Is unordered
  • Can be modified
  • Is written using {}

Example

numbers = {1, 2, 3, 4, 5}
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 3, 4, 5}

Why Do We Use Sets?

  • remove duplicate values
  • find unique items
  • compare two collections
  • find common values
  • find differences between collections
  • perform mathematical set operations

Creating a Set

  • create a set using curly brackets {}.
numbers = {10, 20, 30, 40}
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{10, 20, 30, 40}

Creating an Empty Set

x = set()

print(x)
Enter fullscreen mode Exit fullscreen mode

Output:
set()

Set with Different Data Types

  • A set can contain different data types.
data = {10, "Python", 20.5, True}

print(data)
Enter fullscreen mode Exit fullscreen mode

A set can contain values such as:

  • Integer
  • Float
  • String
  • Boolean

Duplicate Values in a Set

  • The most important feature of a set is that it does not keep duplicate values.
numbers = {1, 2, 2, 3, 3, 4, 4}
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 3, 4}

Set Indexing

  • Sets are unordered, so we cannot access elements using indexes like a list.
numbers = {10, 20, 30, 40}
print(numbers[0])
Enter fullscreen mode Exit fullscreen mode
  • This will result in an error because sets do not support indexing.

Adding Elements to a Set

  • There are two important methods for adding elements: >
  • add()
  • update()

add()

  • add() adds one element to a set.
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 3, 4}

update()

  • update() adds multiple elements.
numbers = {1, 2, 3}
numbers.update([4, 5, 6])
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Result:
{1, 2, 3, 4, 5, 6}

Removing Elements from a Set

  • Python provides several methods for removing elements: >
  • remove()
  • discard()
  • pop()
  • clear()

remove()

  • remove() removes a specific element.
numbers = {1, 2, 3, 4}
numbers.remove(3)
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 4}

discard()

  • discard() also removes a specific element.
numbers = {1, 2, 3, 4}
numbers.discard(3)
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 4}

pop()

  • pop() removes and returns an arbitrary element from the set.
numbers = {10, 20, 30, 40}
x = numbers.pop()
print(x)
print(numbers)
Enter fullscreen mode Exit fullscreen mode

clear()

  • clear() removes all elements from the set.
numbers = {1, 2, 3, 4}
numbers.clear()
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
set()

Checking Elements in a Set

  • We can use the in operator to check whether an element exists.
numbers = {10, 20, 30, 40}
print(20 in numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
True

Looping Through a Set

  • We can use a for loop to access the elements of a set.
numbers = {10, 20, 30, 40}
for number in numbers:
    print(number)
Enter fullscreen mode Exit fullscreen mode

Set Operations

  • Set operations are one of the most important parts of Sets.

The main operations are:

  • Union
  • Intersection
  • Difference
  • Symmetric Difference

Union

  • Union combines all unique elements from both sets. A = {1, 2, 3, 4} B = {3, 4, 5, 6}

Using union()

result = A.union(B)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 3, 4, 5, 6}

Using | - All unique elements from both sets

result = A | B
print(result)
Enter fullscreen mode Exit fullscreen mode

Intersection

  • Intersection returns the elements that are common to both sets.

Using intersection()

result = A.intersection(B)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output:
{3, 4}

Using & - Common elements

result = A & B
Enter fullscreen mode Exit fullscreen mode

Difference

  • Difference returns elements that are present in the first set but not in the second set.
result = A.difference(B)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2}

Using the '-' operator:

result = A - B
Enter fullscreen mode Exit fullscreen mode

Symmetric Difference

  • Symmetric difference returns elements that are present in either set, but not in both.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A.symmetric_difference(B)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 5, 6}

Using ^:

result = A ^ B

Set Operations – Quick Table

Operation             Meaning              Operator

Union                     All unique elements            |
Intersection              Common elements            &
Difference            Elements only in first set     -
Symmetric Difference      Non-common elements            ^
Enter fullscreen mode Exit fullscreen mode

Subset

  • A set is a subset if all its elements are present in another set.
A = {1, 2, 3, 4}
B = {1, 2}
print(B.issubset(A))
Enter fullscreen mode Exit fullscreen mode

Output:
True

Superset

  • A set is a superset if it contains all elements of another set.
A = {1, 2, 3, 4}
B = {1, 2}
print(A.issuperset(B))
Enter fullscreen mode Exit fullscreen mode

Output:
True

Disjoint Sets

  • Two sets are disjoint if they have no common elements.
A = {1, 2, 3}
B = {4, 5, 6}
print(A.isdisjoint(B))
Enter fullscreen mode Exit fullscreen mode

Output:
True

Set Comprehension

  • Set comprehension is a short way to create a set using a loop-like expression.

Using Set Comprehension

numbers = [1, 2, 3, 4, 5]
squares = {number ** 2 for number in numbers}
print(squares)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 4, 9, 16, 25}

Converting List to Set

  • One common use of sets is removing duplicates from a list.
numbers = [1, 2, 2, 3, 3, 4, 4]
unique_numbers = set(numbers)
print(unique_numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 3, 4}

Converting Set to List

  • We can convert a set back into a list using list().
numbers = {1, 2, 3, 4}
numbers_list = list(numbers)
print(numbers_list)
Enter fullscreen mode Exit fullscreen mode

Important Set Methods

Method                  Purpose

add()                   Adds one element
update()            Adds multiple elements
remove()            Removes an element; error if absent
discard()           Removes an element; no error if absent
pop()                   Removes an arbitrary element
clear()                 Removes all elements
union()                 Combines unique elements
intersection()          Finds common elements
difference()            Finds elements only in the first set
symmetric_difference()  Finds non-common elements
issubset()          Checks subset
issuperset()            Checks superset
isdisjoint()            Checks whether there are no common elements
Enter fullscreen mode Exit fullscreen mode

Set vs List

List                       Set

Uses []                    Uses {}
Allows duplicates      Stores unique elements
Ordered                    Unordered
Supports indexing      Does not support indexing
Supports slicing       Does not support normal indexing/slicing
Good for sequence data     Good for unique data
Example [1,2,3]            Example {1,2,3}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)