Sets and Set Methods
✕Introduction to Sets
- Unordered, Unique, Mutable collection of items separated by comma
,enclosed in{} - Used to lookup larger data
- We can perform set operations like union, intersection, difference, etc.
- Can store only immutable data types
- Doesn't store duplicates, if duplicates are added, only one instance is stored
- Indexing and position related function are invalid since it is unordered
- Example:
{1, 2, 3},{"apple", "banana", "orange"},{1, "hello", (1, 2)}
Creating Sets
my_set = {1, 2, 2, 3}print(my_set)# {1, 2, 3} (duplicates are removed)my_set = {1, "hello", (1, 2)}print(my_set)# {1, "hello", (1, 2)}my_set = {1, [2, 3]}# Raises TypeError since list is mutablemy_set = {"apple", "banana", "orange"}print(my_set)# {'banana', 'orange', 'apple'} (unordered)
Examples:
Set Methods
- Functions that perform operations on sets and return a new set or modify the existing
- Data Related Operations:
add(),update(),remove(),discard(),pop() - Numeric Function:
sum(),min(),max(),len() - General:
sorted(),copy() - Set Operations:
union,intersection,difference,symmetric_difference
add
- Used to add an element to a set
- Syntax:
set_name.add(element) my_set = {1, 2, 3}my_set.add(4)print(my_set)# {1, 2, 3, 4}my_set.add(2)print(my_set)# {1, 2, 3, 4} (adding duplicate doesn't change the set)my_set.add([5, 6])# Raises TypeError since list is mutable
Examples:
update
- For adding multiple elements to a set from an iterable (list, tuple, etc)
like extend of list - Syntax:
set_name.update(iterable) my_set = {1, 2, 3}my_set.update([4, 5])print(my_set)# {1, 2, 3, 4, 5}my_set.update((6, 7))print(my_set)# {1, 2, 3, 4, 5, 6, 7}my_set.update({8, 9})print(my_set)# {1, 2, 3, 4, 5, 6, 7, 8, 9}my_set.update("hello")print(my_set)# {1, 2, 3, 4, 5, 6, 7, 'h', 'e', 'l', 'o'} (string is treated as an iterable of characters)
Examples:
remove and discard
- Used to remove an element from a set
remove()gives error if the element is not found butdiscard()does not- Syntax:
set_name.remove(element);set_name.discard(element) my_set = {1, 2, 3, 4}my_set.remove(2)print(my_set)# {1, 3, 4}my_set.remove(5)# Raises KeyError since element is not foundmy_set.discard(3)print(my_set)# {1, 4}my_set.discard(5)# No error raised even though element is not foundprint(my_set)# {1, 4}
Examples:
pop
- Used to remove and return an arbitrary element from a set
- Syntax:
set_name.pop() my_set = {1, 2, 3, 4}removed_element = my_set.pop()print(removed_element)# Could be any element from the setprint(my_set)# Set with one less element
Examples:
Numeric Functions
- Used to perform numeric operations on sets containing numbers
- Valid Functions:
sum(only for int and float sets),min,max,len num_set = {1, 2, 3, 4, 5}print(sum(num_set))# 15print(min(num_set))# 1print(max(num_set))# 5print(len(num_set))# 5
Examples:
Sorted
- Used to sort the elements of a set in ascending order by default
sorted()function is used sincesort()method modifies in-placemy_set = {3, 1, 4, 2}sorted_set = sorted(my_set)print(sorted_set)# [1, 2, 3, 4]print(my_set)# {1, 2, 3, 4} (original set remains unchanged)str_set = {"apple", "ball", "cat"}sorted_str_set = sorted(str_set, reverse=True)print(sorted_str_set)# ['cat', 'ball', 'apple'] (sort in descending order)sorted_str_set = sorted(str_set, key=len)print(sorted_str_set)# ['ball', 'cat', 'apple'] (sort by length of strings)
Examples:
Copying Sets
- Used to create a copy of a set to avoid modifying the original set
original_set = {1, 2, 3}copied_set = original_setcopied_set.add(4)print(original_set)# {1, 2, 3}print(copied_set)# {1, 2, 3}another_copy = original_set.copy()another_copy.add(5)print(original_set)# {1, 2, 3}print(another_copy)# {1, 2, 3, 5}`
Examples:
Set Operations
- Used to perform mathematical set operations like union, intersection, difference, etc.
- Valid Functions:
union,intersection,difference,symmetric_difference set_a = {1, 2, 3}set_b = {3, 4, 5}print(set_a.union(set_b))# {1, 2, 3, 4, 5} orset_a | set_bprint(set_a.intersection(set_b))# {3} orset_a & set_bprint(set_a.difference(set_b))# {1, 2} orset_a - set_bprint(set_a.symmetric_difference(set_b))# {1, 2, 4, 5} orset_a ^ set_b
Examples:
Frozenset
- Immutable version of a set, created using
frozenset()function - Once created, elements cannot be added or removed
my_frozenset = frozenset([1, 2, 3])print(my_frozenset)# frozenset({1, 2, 3})my_frozenset.add(4)# Raises AttributeError since frozenset is immutableprint(my_frozenset)# frozenset({1, 2, 3})
Examples:
