DEV Community

Sowntharya
Sowntharya

Posted on

Master Python Sets

A set object is an unordered collection of distinct hashable objects.

In Python, a Set is a built-in data type used to store multiple unique elements in a single variable.

Sets are unordered collections, which means they do not maintain a fixed position for their elements. They also do not allow duplicate values.

Sets are useful when we want to store unique data and perform operations like union, intersection and difference.

1. Creating a Set

A set is created using curly brackets {} or the set() function.

s = {10, 20, 30, 40, 50}

print(s)
print(type(s))
print(len(s))
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40, 50}
<class 'set'>
5
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • {} is used to create a set with elements.
  • type() identifies the data type.
  • len() returns the number of elements.

2. Duplicate Elements in Sets

Sets automatically remove duplicate values.

s = {10, 20, 30, 10, 20, 40}

print(s)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40}
Enter fullscreen mode Exit fullscreen mode

Explanation: Duplicate elements are automatically removed, so each value appears only once.

3. Creating an Empty Set

To create an empty set, we must use set().

s = set()

print(s)
print(type(s))
Enter fullscreen mode Exit fullscreen mode

Output:

set()
<class 'set'>
Enter fullscreen mode Exit fullscreen mode

Note: {} creates an empty dictionary, not an empty set.

4. Adding Elements to a Set

We can use the add() method to insert a single element.

s = {10, 20, 30}

s.add(40)

print(s)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40}
Enter fullscreen mode Exit fullscreen mode

5. Adding Multiple Elements Using update()

The update() method adds multiple elements from another iterable.

s = {10, 20, 30}

s.update([40, 50, 60])

print(s)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40, 50, 60}
Enter fullscreen mode Exit fullscreen mode

6. Removing Elements from a Set

Python provides different methods to remove elements.

Using remove():

s = {10, 20, 30, 40}

s.remove(20)

print(s)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 30, 40}
Enter fullscreen mode Exit fullscreen mode

Using discard():

s = {10, 20, 30, 40}

s.discard(50)

print(s)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40}
Enter fullscreen mode Exit fullscreen mode

Difference:

  • remove() raises a KeyError if the element does not exist.
  • discard() does not raise an error if the element is missing.

7. Set Operations

Set operations are one of the most important features of Python sets.

Union ( | )

Union combines all unique elements from two sets.

a = {10, 20, 30}
b = {30, 40, 50}

print(a | b)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 30, 40, 50}
Enter fullscreen mode Exit fullscreen mode

Intersection ( & )

Intersection returns only the common elements.

a = {10, 20, 30}
b = {30, 40, 50}

print(a & b)
Enter fullscreen mode Exit fullscreen mode

Output:

{30}
Enter fullscreen mode Exit fullscreen mode

Difference ( - )

Difference returns elements present in the first set but not in the second set.

a = {10, 20, 30}
b = {30, 40, 50}

print(a - b)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20}
Enter fullscreen mode Exit fullscreen mode

Symmetric Difference ( ^ )

Returns elements that are present in either set, but not in both.

a = {10, 20, 30}
b = {30, 40, 50}

print(a ^ b)
Enter fullscreen mode Exit fullscreen mode

Output:

{10, 20, 40, 50}
Enter fullscreen mode Exit fullscreen mode

8. Checking Elements Using Membership Operators

We can use in and not in to check whether an element exists in a set.

s = {10, 20, 30, 40}

print(20 in s)
print(50 not in s)
Enter fullscreen mode Exit fullscreen mode

Output:

True
True
Enter fullscreen mode Exit fullscreen mode

9. Set Methods

Some commonly used set methods are:

Method Description
add() Adds a single element
update() Adds multiple elements
remove() Removes an element; raises an error if missing
discard() Removes an element without an error if missing
pop() Removes and returns an arbitrary element
clear() Removes all elements
copy() Creates a shallow copy
union() Combines two sets
intersection() Returns common elements
difference() Returns elements in the first set only
symmetric_difference() Returns non-common elements

10. Frozenset in Python

A frozenset is an immutable version of a set. Once created, its elements cannot be added or removed.

s = frozenset([10, 20, 30, 40])

print(s)
print(type(s))
Enter fullscreen mode Exit fullscreen mode

Output:

frozenset({10, 20, 30, 40})
<class 'frozenset'>
Enter fullscreen mode Exit fullscreen mode

Explanation: Unlike normal sets, frozensets do not support modification methods such as add() and remove().

11. Difference Between List, Tuple and Set

Feature List Tuple Set
Syntax [] () {}
Ordering Ordered Ordered Unordered
Mutability Mutable Immutable Mutable
Duplicates Allowed Allowed Not allowed
Indexing Supported Supported Not supported
Usage Dynamic data Fixed data Unique data

Conclusion

Sets are an important data structure in Python. They help us store unique elements and perform mathematical operations easily.

Top comments (0)