Set Datatype In Python

The Set Datatype in Python is a powerful data structure used to store unique and unordered elements. Unlike lists and tuples, sets automatically remove duplicate values, making them ideal for membership testing and mathematical operations.

Additionally, Python sets support operations such as union, intersection, difference, and symmetric difference. Therefore, they are widely used in data processing, analytics, and software development.

learn how to create sets, use set methods, perform set operations, and work with frozen sets through practical examples.

What is Python Set?

A Python Set is a built-in data type used to store multiple unique values in a single collection. A set is enclosed within curly braces {} and each element is separated by a comma.

Unlike lists and tuples, sets do not allow duplicate values. Therefore, they are useful when you need to store only unique elements and perform fast membership checks.

Key Characteristics of Python Sets

  • Unique Elements : Python sets store only unique values. Therefore, Python automatically removes duplicate elements when you add them to a set.
  • Unordered Collection: Sets do not maintain the order of elements. However, you can sort the elements whenever you need an ordered output.
  • No Indexing or Slicing: Sets do not support indexing or slicing because they are unordered collections. As a result, you cannot access elements by position.
  • Heterogeneous Elements: A set can store different data types, including integers, strings, floats, and tuples. Additionally, this flexibility makes sets useful for many programming tasks.
  • Mutable: You can modify a set after creating it. For example, you can add new elements or remove existing ones whenever required.
  • Mathematical Operations :Sets support mathematical operations such as union, intersection, difference, and symmetric difference. Consequently, developers frequently use sets for data analysis and problem-solving.

Python Sets Creation

1. Empty Set:

An empty set can only be created by using the set() function, as {} creates an empty dictionary.

empty_set = set()
print(empty_set)

Output:

set()

2. Using Curly Braces:

my_set = {1, 2, 3, 4}
print(my_set)  

Output:

{1, 2, 3, 4}

3. Using the set() function:

# From a list
my_set = set([10, 20, 30])
print(my_set)

# From a range
my_set = set(range(5))
print(my_set)  

Output:

{10, 20, 30}
{0, 1, 2, 3, 4}

Note: s={} ==>It is treated as a dictionary but not the empty set.

Common Set Functions

FunctionDescriptionExampleOutput
len(set)Returns the number of elements in a set.len({1, 2, 3})3
min(set)Returns the smallest element in the set.min({5, 2, 9, 1})1
max(set)Returns the largest element in the set.max({5, 2, 9, 1})9
sorted(set)Returns a sorted list from the elements of the set.sorted({3, 1, 2})[1, 2, 3]
reversed(set)Not applicable for sets (as sets are unordered).N/AN/A

Note: reversed() does not work with sets because sets are unordered collections, so there is no defined sequence to reverse.

Examples Using All Functions Together:

my_set = {10, 3, 6, 8}

# len() - Get the number of elements in the set
print(f"Length of the set: {len(my_set)}")

# min() - Get the smallest element in the set
print(f"Smallest element: {min(my_set)}")

# max() - Get the largest element in the set
print(f"Largest element: {max(my_set)}")

# sorted() - Sort the set and return a list
print(f"Sorted set: {sorted(my_set)}")

# reversed() - Not applicable, would raise an error if tried.

Output:

Length of the set: 4
Smallest element: 3
Largest element: 10
Sorted set: [3, 6, 8, 10]

Set Methods

MethodDescriptionExample Code
add(item)Adds a single element to the set.s.add(10)
update(iterable)Adds multiple elements from an iterable.s.update([20, 30])
remove(item)Removes the specified element. returns error if not found.s.remove(10)
discard(item)Removes the element if present; no error if not found.s.discard(15)
pop()Removes and returns an arbitrary element.s.pop()
clear()Removes all elements from the set.s.clear()
union(set2)Returns the union of two sets.s.union(s2)
intersection(set2)Returns the intersection of two sets.s.intersection(s2)
difference(set2)Returns the difference between two sets.s.difference(s2)
symmetric_difference(set2)Returns elements in either set but not both.s.symmetric_difference(s2)
issubset(set2)Checks if one set is a subset of another.s.issubset(s2)
issuperset(set2)Checks if one set is a superset of another.s.issuperset(s2)
isdisjoint(set2)Checks if two sets have no elements in common.s.isdisjoint(s2)

** We can see all methods in list by using dir(list) predefined function.

Examples of all methods

1. Adding Elements to a Set

  • add(item): Adds a single element to the set.
  • update(iterable): Adds multiple elements from an iterable (e.g., list, set).
s = {1, 2, 3}
s.add(4)  # Adding a single element
print(s)

s.update([5, 6, 7])  # Adding multiple elements from a list
print(s)

Output:

{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7}

2. Removing Elements from a Set

  • remove(item): Removes the specified element. Returns error if it is not found.
  • discard(item): Removes the element if present. No error if the element is not found.
  • pop(): Removes and returns an arbitrary or random element from the set.
  • clear(): Removes all elements from the set.
s = {1, 2, 3, 4}
s.remove(2)  # Removes 2
print(s)

s.discard(10)  # No error even though 10 is not in the set
print(s) 

print(s.pop())  # Removes and prints an arbitrary element
print(s)

s.clear()  # Clears the set
print(s)

Output:

{1, 3, 4}
{1, 3, 4}
1
{3, 4}
set()

3. Mathematical Set Operations

  • union(set2): Returns a set containing all elements from both sets.
  • intersection(set2): Returns a set containing only elements common to both sets.
  • difference(set2): Returns elements in the first set but not in the second.
  • symmetric_difference(set2): Returns elements in either set but not in both.
s1 = {1, 2, 3}
s2 = {3, 4, 5}

print(s1.union(s2))
print(s1.intersection(s2))
print(s1.difference(s2))
print(s1.symmetric_difference(s2))

Output:

{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
s1 = {1, 2, 3}
s2 = {3, 4, 5}

print(s1 | s2)
print(s1 & s2)
print(s1 - s2)
print(s1 ^ s2)

Output:

{1, 2, 3, 4, 5} # Union
{3}             # Intersection
{1, 2}          # Difference
{1, 2, 4, 5}    # Symmetric difference

4. Set Relations and Comparisons

Python provides several methods to compare sets and understand their relationships. These methods help determine whether sets share elements or whether one set is contained within another.

  • issubset(set2): Checks if one set is a subset of another.
  • issuperset(set2): Checks if one set is a superset of another.
  • isdisjoint(set2): Checks if two sets have no common elements.
s1 = {1, 2}
s2 = {1, 2, 3}

print(s1.issubset(s2))
print(s2.issuperset(s1))

s3 = {4, 5}
print(s1.isdisjoint(s3))

Output:

True
True
True

5. Copying Sets

  • copy(): it creates and returns a shallow copy of a set.
s1 = {1, 2, 3}
s_copy = s1.copy()
print(s_copy)

Output:

{1,2,3}

Membership Operators: (in, not in)

We can check whether a given element exists in a set or not using these operators

  • in: Checks if an element is present in the set.
  • not in: Checks if an element is absent from the set.
s = set("apple")
print(s)
print('a' in s)
print('z' in s)

Output:

{'p', 'a', 'e', 'l'}
True
False

Set Comprehension

We can generate sets using set comprehension just like list comprehension but with curly braces {}.

# Set of squares
st1 = {x*x for x in range(5)}
print(st1)

# Set of powers of 2
st2 = {2**x for x in range(2, 10, 2)}
print(st2)

Output:

{0, 1, 4, 9, 16}
{16, 256, 64, 4}

Frozen Set

A frozen set is an immutable version of a Python set. It works like a regular set, but its elements cannot be modified after creation. As a result, frozen sets are hashable and can be used as dictionary keys or elements of other sets.

Key Characteristics of Frozen Sets

  • Immutable: Once a frozen set is created, you cannot add, remove, or update its elements.
  • Hashable: Because frozen sets are immutable, they can safely be used as dictionary keys or stored inside other sets.
  • Unordered: Similar to regular sets, frozen sets do not maintain the order of elements.
  • No Duplicate Values: Frozen sets store only unique elements. Therefore, duplicate values are automatically removed.

Why Use Frozen Sets?

Frozen sets are useful when you need a collection of unique values that should remain unchanged. Additionally, they provide a reliable way to use sets as dictionary keys or nested set elements.

Creating a Frozen Set:

We can create a frozen set using the frozenset() pre-defined function:

# Creating a frozen set from a list
frozen_set = frozenset([1, 2, 3, 4])
print(frozen_set)

# Creating a frozen set from a string
frozen_set_from_str = frozenset("hello")
print(frozen_set_from_str)

Output:

frozenset({1, 2, 3, 4})
frozenset({'o', 'l', 'e', 'h'})

Conclusion

The Set Datatype in Python is an efficient way to store and manage unique elements. Additionally, it provides powerful operations such as union, intersection, and difference. By understanding sets and frozen sets, developers can write cleaner, faster, and more efficient Python programs.

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python

Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id1611034268

What is a Set Datatype in Python?


A Set Datatype in Python stores unique and unordered elements. It automatically removes duplicate values and supports mathematical set operations.

Why are sets used in Python?

Sets are used for storing unique values and performing fast membership checks. Additionally, they support union, intersection, and difference operations.

What is a frozen set in Python?

A frozen set is an immutable version of a set. Therefore, its elements cannot be added, removed, or modified after creation.

What is the difference between a set and a list in Python?

A list stores ordered elements and allows duplicates. However, a set stores unordered unique elements and removes duplicates automatically.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *