Learning Python Part-16: Python Sets along with Frozenset

Python sets are unordered collection of unique items unlike lists or tuples. Python sets are defined by values separated by comma inside curly braces {}. The sets are mutable so we can add or remove elements to/from it. However, elements in a set are not ordered.

Example:

a = {1, 2, 3, 4, 5}

print(a)                                     #### Output a = {5,2,3,1,4}
print(type(a))                            #### Output will be


Python sets eliminate the duplicates as shown in below example.

a = {1,2,2,3,3,3}
print(a)                                      ### Output will be {1, 2, 3}

Slicing operator [] does not work on set since they are unordered in nature.

Sets can be used to perform mathematical set operations like union, intersection, symmetric difference. A set can have any number of items and they may be of different types (integer, float, tuple, string etc).

But a set cannot have a mutable element, like list, set or dictionary, as its element.

# set of integers

s = {1, 2, 3}
print(s)

# set of mixed datatypes

s = {1.0, “Hello”, (1, 2, 3)}
print(s)

s = set([1,2,3,2])
print(s)


How to change a set in Python?

  • Sets are mutable. But since they are unordered, indexing does not work with sets.
  • We cannot access/change an element of set using indexing or slicing. Set does not support it.
  • We can add single element using the add() method and multiple elements using the update() method. 
  • The update() method can take tuples, lists, strings or other sets as its argument as in examples below. However, in all cases duplicates are avoided.

s = {1,3}
print(s)

# add an element

s.add(2)
print(s)

# add multiple elements

s.update([2,3,4])
print(s)

# add list and set

s.update([4,5], {1,6,8})
print(s)


How to remove elements from a set?

  • A particular item can be removed from set using methods like discard() and remove().
  • The only difference between the two methods is that, while using discard() if the item does not exist in the set, it remains unchanged. 
  • But remove() will raise an error in such condition.

s = {1, 3, 4, 5, 6}

s.discard(4)
print(s)

s.remove(6)
print(s)

s.discard(2)
print(s)

  • Similarly, we can remove and return an item using the pop() method.

print(s.pop())


  • Be careful with pop(). Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.

s.pop()

  • We can also remove all items from a set using clear().

s.clear()


Python Set Operations:

  • Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. 
  • We can do these operations using operators or methods.
    • Set Union
    • Set Intersection
    • Set Difference
    • Set Symmetric Difference
  • Set Union:

  • Union of set A and set B is a set of all elements from both sets.
  • Union is performed using ‘ | ‘ operator. 
  • Same can be accomplished using the method union().
  • Example:
# initialize set A and set B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)                                   # use of | operator
                                                     # Output: {1, 2, 3, 4, 5, 6, 7, 8}
OR

print(A.union(B))            # Output: 
{1, 2, 3, 4, 5, 6, 7, 8}

# or other way, use union function on B

print(B.union(A))           
# Output: {1, 2, 3, 4, 5, 6, 7, 8}

  • Set Intersection:

  • Intersection of set A and set B is a set of elements that are common in both sets.
  • Intersection is performed using ‘&‘ operator. 
  • Same can be accomplished using the method intersection().

# initialize A and B

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A & B)                                      # use & operator. # Output: {4, 5}

# use intersection function on A

print(A.intersection(B))                    # Output : {4, 5}

# Or use intersection function on B

print(B.intersection(A))                    # Output: {4, 5}


  • Set Difference:

  • Difference of set A & set B is a set of elements that are only in A but not in B or vice versa. 
  • ex: B – A is a set of element in B but not in A
  • ex A – B is a set of element in A but not in B.
  • Difference is performed using ‘‘ operator. 
  • Same can be accomplished using the method difference().

# initialize A and B

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A – B)                                         # use – operator on A # Output: {1, 2, 3}

# use difference function on A

print(A.difference(B))                         # Output:  {1, 2, 3}

# use – operator on B

print(B – A )                                         # Output: {8, 6, 7}

# use difference function on B

print(B.difference(A))                          # Output: {8, 6, 7}


  • Set Symmetric Difference:

  • Symmetric Difference of A and B is a set of elements in both A and B except those elements that are common in both.
  • Symmetric difference is performed using ‘^‘ operator. 
  • Same can be accomplished using the method symmetric_difference().

# initialize A and B

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A ^ B)                                                # use ^ operator. # Output: {1, 2, 3, 6, 7, 8}

# use symmetric_difference function on A

print(A.symmetric_difference(B))              # Output:  {1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B

print(B.symmetric_difference(A))               # Output:  {1, 2, 3, 6, 7, 8}

Different Python Set Methods:



Other Set Operations:


  • Set Membership Test
    • We can test if an item exists in a set or not, using the keyword in.

s = set(“apple”)
print(‘a’ in s)                    # Output: True
print(‘p’ not in s)              # Output: False

  • Iterating Through a Set

for x in set(“apple”):
       print(x)


Built-in Functions with Set:


Python Frozenset:
  • Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. 
  • While tuples are immutable lists, frozensets are immutable sets.
  • Sets being mutable are unhashable, so they can’t be used as dictionary keys. 
  • On the other hand, frozensets are hashable and can be used as keys to a dictionary.
  • Frozenset supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). 
  • Being immutable it does not have method that add or remove elements.
  • Frozensets can be created using the frozenset() function.

# initialize A and B

A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

print(A.isdisjoint(B))                             # Output:  False
print(A.difference(B))                            # Output:  frozenset({1, 2}) 


print(A | B)                                             # Output:  frozenset({1, 2, 3, 4, 5, 6})

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.