Python for Beginners : Exploring Sets in Python - A Guide to Unique and Unordered Collections

Python for Beginners : Exploring Sets in Python - A Guide to Unique and Unordered Collections

Sets are one of Python’s powerful data structures that allow you to store unique, unordered elements. They are ideal for operations like removing duplicates, performing mathematical set operations, or managing data where order doesn’t matter.

What is a Set in Python?

A set is a collection of unique and unordered items. This means that:

  • A set cannot have duplicate elements.
  • The elements in a set are not stored in a specific order.

Set Characteristics

  1. Mutable: You can add or remove elements from a set.
  2. Unordered: Sets don’t maintain the order of elements.
  3. No Duplicates: Duplicate values are automatically removed.

Creating a Set

You can create a set by using curly braces {} or the set() function.

my_set = {1, 2, 3, 4}                               # Using curly braces
empty_set = set()                                  # Creates an empty set        

Why Use Sets?

  1. Remove Duplicates: Sets automatically handle duplicates, making them useful for filtering unique elements.

numbers = [1, 2, 2, 3, 4, 4]
unique_numbers = set(numbers)
print(unique_numbers) 
----------------------------------------------------------
Output: {1, 2, 3, 4}        

2. Perform Mathematical Set Operations:

Sets allow union, intersection, and difference operations efficiently.

3. Fast Membership Testing:

Checking if an element exists in a set is faster compared to lists.

print(3 in {1, 2, 3, 4}) 
-----------------------------------------------------------
Output: True        

Set Methods :

Here’s a table of common set methods with syntax and examples:

1) add() : Adds an element to the set.

Syntax: set.add(value)

my_set = {1, 2} 
my_set.add(3) 
print(my_set) 
-----------------------------------------------------------------------
Output: {1, 2, 3}        

If the element already exists, it does nothing.

my_set = {1, 2} 
my_set.add(2) 
print(my_set) 
--------------------------------------------------------------------------
Output: {1, 2,}        

2) remove() : Removes the specified element.

Syntax: set.remove(value)

my_set = {1, 2, 3} 
my_set.remove(2) 
print(my_set)
----------------------------------------------------------------------
 Output: {1, 3}        

Raises an error if the element is not present.

my_set = {1, 2, 3} 
my_set.remove(4) 
print(my_set)
------------------------------------------------------------------------
 Output: KeyError  #It throws an error as 4 is not in my_set        

3) discard() : Removes the specified element if it exists. Does not raise an error if the element is absent.

Syntax : set.discard(value)

my_set = {1, 2, 3} 
my_set.discard(4) 
print(my_set) 
-------------------------------------------------------------
Output: {1, 2, 3}        

4. pop() : Removes and returns an arbitrary element from the set. Raises an error if the set is empty.

Syntax: set.pop()

my_set = {1, 2, 3} 
print(my_set.pop())        

5. clear() : Removes all elements from the set, leaving it empty.

Syntax: set.clear()

my_set = {1, 2, 3} 
my_set.clear()
print(my_set) 
----------------------------------------------------
Output: set()        

6. union() : Returns a new set with all unique elements from both sets.

Syntax : set.union(other_set)

set1 = {1, 2} 
set2 = {3, 4, "hi"} 
print(set1.union(set2)) 
----------------------------------------------------------------
Output: {1, 2, 3, 'hi',4}        

7. intersection() : Returns a new set with elements common to both sets.

Syntax : set.intersection(other_set)

set1 = {1, 2, 3} 
set2 = {2, 3, 4} 
print(set1.intersection(set2)) 
-------------------------------------------------------------------------
Output: {2, 3}        

8. difference() : Returns a new set with elements from the first set not in the second.

Syntax : set.difference(other_set)

set1 = {1, 2, 3} 
set2 = {2, 3, 4} 
print(set1.difference(set2)) 
-------------------------------------------------------
Output: {1}        

9. isdisjoint() : Checks if two sets have no elements in common. Returns True if disjoint, else False.

Syntax : set.isdisjoint(other_set)

set1 = {1, 2} 
set2 = {3, 4} 
print(set1.isdisjoint(set2)) 
----------------------------------------------------
Output: True        

Operations on Sets

1. Union

Combines elements from both sets without duplicates.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2)  
-------------------------------
Output: {1, 2, 3, 4, 5}        

2. Intersection

Finds common elements between sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2)  
----------------------------------
Output: {3}        

3. Difference

Finds elements in one set that are not in the other.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 - set2)  
--------------------------------------------------------
Output: {1, 2}        

4. Symmetric Difference

Finds elements in either set, but not in both.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 ^ set2)  
---------------------------------------------------------
Output: {1, 2, 4, 5}        

Immutability with Frozensets

Python also provides an immutable version of sets called frozenset.

immutable_set = frozenset([1, 2, 3])        

Practical Applications of Sets

  1. Removing Duplicates from a List:

data = [1, 2, 2, 3, 4, 4, 'hi']
unique_data = list(set(data))
print(unique_data)  
--------------------------------------------------------
 Output: [1, 2, 3, 4, 'hi']        

Finding Common Items in Two Lists:

list1 = [1, 2, 3]
list2 = [2, 3, 4]
print(set(list1) & set(list2))  
------------------------------------------------------------
Output: {2, 3}        

Efficient Membership Testing:

elements = {100, 200, 300}
print(200 in elements)  
--------------------------------------------------------------
Output: True        

Sets in Python are an excellent choice when working with unique data or performing mathematical operations. Their speed and efficiency in handling large datasets make them a must-have tool in your programming toolkit.

In the next article, we will explore Dictionaries in Python, another versatile data structure for key-value pair management. Stay tuned!

To view or add a comment, sign in

Explore content categories