Mastering Python Sets: Your Ultimate Guide to Efficient Data Handling.

Learn everything about Python sets in this beginner-to-advanced tutorial. Explore unique elements, set operations, and frozen sets with examples!

Python Sets
Python Sets

A group of data is enclosed in a curly =brace {} and each value is separated by a comma.

Key Characteristics of Python Sets

  • Unique Elements: Sets store unique values, meaning duplicates are not allowed.
  • Unordered: Sets do not preserve insertion order, but you can sort the elements.
  • No Indexing or Slicing: You cannot access elements by index or slice in a set.
  • Heterogeneous Elements: Sets can store elements of different data types.
  • Mutable: Set objects can be modified after creation (elements can be added or removed).
  • Mathematical Operations: Sets support operations like union, intersection, and difference.

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)  # Output: {10, 20, 30}

# From a range
my_set = set(range(5))
print(my_set)  # Output: {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)}")  # Output: 4

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

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

# sorted() - Sort the set and return a list
print(f"Sorted set: {sorted(my_set)}")  # Output: [3, 6, 8, 10]

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

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)  # Output: {1, 2, 3, 4}

s.update([5, 6, 7])  # Adding multiple elements from a list
print(s)  # Output: {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 element from the set.
  • clear(): Removes all elements from the set.
s = {1, 2, 3, 4}
s.remove(2)  # Removes 2
print(s)  # Output: {1, 3, 4}

s.discard(10)  # No error even though 10 is not in the set
print(s)  # Output: {1, 3, 4}

print(s.pop())  # Removes and prints an arbitrary element
print(s)  # Output: Remaining elements

s.clear()  # Clears the set
print(s)  # Output: 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))  # Output: {1, 2, 3, 4, 5}
print(s1.intersection(s2))  # Output: {3}
print(s1.difference(s2))  # Output: {1, 2}
print(s1.symmetric_difference(s2))  # Output: {1, 2, 4, 5}
s1 = {1, 2, 3}
s2 = {3, 4, 5}

print(s1 | s2)  # Union: Output: {1, 2, 3, 4, 5}
print(s1 & s2)  # Intersection: Output: {3}
print(s1 - s2)  # Difference: Output: {1, 2}
print(s1 ^ s2)  # Symmetric difference: Output: {1, 2, 4, 5}

4. Set Relations and Comparisons

  • 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))  # Output: True
print(s2.issuperset(s1))  # Output: True

s3 = {4, 5}
print(s1.isdisjoint(s3))  # Output: True

5. Copying Sets

  • copy(): Creates and returns a shallow copy of the 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 an given element exists in a set using membership 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)            # Output: {'p', 'e', 'l', 'a'}
print('a' in s)     # Output: True
print('z' in s)     # Output: False

Set Comprehension:

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

# Set of squares
s = {x*x for x in range(5)}
print(s)  # Output: {0, 1, 4, 9, 16}

# Set of powers of 2
s = {2**x for x in range(2, 10, 2)}
print(s)  # Output: {4, 16, 64, 256}

Frozen Set:

A frozen set is a data type that represents an immutable version of a set. It is similar to a regular set, but unlike sets, frozen sets cannot be modified after creation, making them hashable and usable as dictionary keys or set elements.

  • Immutable: Once created, you cannot add or remove elements from a frozen set.
  • Hashable: Because they are immutable, frozen sets can be used as keys in dictionaries and elements in other sets.
  • Unordered: Like regular sets, frozen sets do not maintain the order of elements.
  • No Duplicates: They cannot contain duplicate 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)  # Output: frozenset({1, 2, 3, 4})

# Creating a frozen set from a string
frozen_set_from_str = frozenset("hello")
print(frozen_set_from_str)  # Output: frozenset({'h', 'e', 'l', 'o'})

Conclusion

Sets are powerful tools in Python for handling collections of unique elements. Their built-in operations make them efficient for tasks involving membership tests, unions, intersections, and more.

Check out our full Python guide here. : Learn From KSR Datavizon | Explore and Read Our Blogs Written By Our Industry Expert

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

Related Posts

Leave a Reply

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