• A set is a collection of data types in Python, the same as the list and tuple. However, it is not an ordered collection of objects.
  • The set is a Python implementation of the set in Mathematics.
  • The elements of the set are unordered, so we can not access it by indexing and slicing.
  • A set object has suitable methods to perform mathematical set operations like union, intersection, difference, etc.
  • Set elements are separated by a comma and enclosed in curly brackets {}.
  • A set is a mutable data type.
Syntax: set = {value1, value2, value3,…valueN}

Example:

s1 = {1, "Bill", 75.50}  # supports heterogeneous data type
print (s1)

[out: ]
{1, 75.5, 'Bill'}
  • A set doesn’t store duplicate objects. Even if an object is added more than once inside the curly brackets, only one copy is held in the set object. Hence, indexing and slicing operations cannot be done on a set object.
s1 = {6,1, 2, 2, 3, 4, 4, 5, 5}
print (s1)

[out: ]
{1, 2, 3, 4, 5, 6}

Operations on Sets

  • | :: union()

Returns the union of sets in a new set.

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

print (s1|s2)
print (s1.union(s2))

[out: ]
{1, 2, 3}
{1, 2, 3}
  • & :: intersection()

The intersection of two sets is a set containing elements common to both collections.

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

print (s1 & s2)
print (s1.intersection(s2))

[out: ]
{2}
{2}
  • – :: difference()

The difference of two sets results in a set containing elements only in the first set, but not in the second set.

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

print (s1-s2)
print (s1.difference(s2))

[out: ]
{1}
{1}
print (s2-s1)
print (s2.difference(s1))

[out: ]
{3}
{3}
  • ^ :: Symmetric_difference()

The result of the symmetric difference is a set consisting of elements in both sets, excluding the common elements.

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

print(s1 ^ s2)
print(s1.symmetric_difference(s2))

[out: ]
{1, 3}
{1, 3}

Built-in Set Methods

  • set() :: Convert anything into set using set() function.
# Converting string into set

str = "Python"
s1 = set(str)
print (s1)

[out: ]
{'P', 'o', 'h', 'y', 'n', 't'}
# Converting list into set

lst = [45,67,87,36, 55]
s1 = set(lst)
print (s1)

[out: ]
{67, 36, 45, 87, 55}
# Converting tuple into set

tup1 = (10,25,15)
s1 = set(tup1)
print (s1)

[out: ]
{25, 10, 15}

Note: The order of elements in the set is not necessarily the same as the order given at the time of assignment. Python optimizes the structure of a set for performing operations over it, as defined in mathematics.

  • add() :: Adds a new element to the set
s1 = {1,2}
s1.add(3)

print ("s1:",s1)

[out: ]
s1: {1, 2, 3}
  • clear() :: Removes all elements from the set
s1 = {1,2}

s1.clear()
print ("s1:",s1)

[out: ]
s1: set()
  • copy() :: Returns a copy of the set
s1 = {1,2}
print (s1.copy())

[out: ]
{1, 2}
  • discard() :: Removes an element from the set if it is a member. (Do nothing if the element is not in set)
s1 = {1,2}

s1.discard(2)
print ("s1:",s1)

[out: ]
s1: {1}
s1.discard(4)   # 4 is not member of the set
print ("s1:",s1)

[out: ]
s1: {1}
  • remove() :: Removes an element from the set. If the element is not a member, raise a KeyError.
s1 = {1,2,3}

s1.remove(3)
print (s1)

[out: ]
{1, 2}
s1.remove(4)    # 4 is not member of the set, so raise a KeyError.
print (s1)

[out: ]
  • pop() :: Removes and returns an arbitary set element. Raise KeyError if the set is empty.
s1 = {1,2,3}
s1.pop()
print (s1)

[out: ]
{2, 3}
  • difference_update() :: Removes all elements of another set from this set
s1 = {1,2}
s2 = {2,3}

s1.difference_update(s2)
print ("s1:",s1)
print ("s2:",s2)

[out: ]
s1: {1}
s2: {2, 3}
s1 = {1,2}
s2 = {2,3}

s2.difference_update(s1)
print ("s1:",s1)
print ("s2:",s2)

[out: ]
s1: {1, 2}
s2: {3}
  • intersection_update() :: Updates the set with the intersection of itself and another
s1 = {1,2,3}
s2 = {2,3,4}

s1.intersection_update(s2)
print ("s1:",s1)
print ("s2:",s2)

[out: ]
s1: {2, 3}
s2: {2, 3, 4}
s1 = {1,2,3}
s2 = {2,3,4}

s2.intersection_update(s1)
print ("s1:",s1)
print ("s2:",s2)

[out: ]
s1: {1, 2, 3}
s2: {2, 3}
  • isdisjoint() :: ReturnsTrue if two sets have a null intersection
s1 = {1,2}
s2 = {3,4}
print (s1.isdisjoint(s2))

[out: ]
True
s1 = {1,2}
s2 = {2,3}
print (s2.isdisjoint(s1))

[out: ]
False
  • issubset() :: ReturnsTrue if another set contains this set
s1 = {1,2,3}
s2 = {3}

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

[out: ]
False
True
  • issuperset() :: ReturnsTrue if this set contains another set
s1 = {1,2,3}
s2 = {3}

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

[out: ]
True
False
  • symmetric_difference_update() :: Updates a set with the symmetric difference of itself and another
s1 = {1,2,3}
s2 = {3,4,5}

s1.symmetric_difference_update(s2)
print (s1)
print (s2)

[out: ]
{1, 2, 4, 5}
{3, 4, 5}
s1 = {1,2,3}
s2 = {3,4,5}

s2.symmetric_difference_update(s1)
print (s1)
print (s2)

[out: ]
{1, 2, 3}
{1, 2, 4, 5}
  • update() :: Updates the set with the union of itself and others
s1 = {1,2,3}
s2 = {3,4,5}

s1.update(s2)
print (s1)
print (s2)

[out: ]
{1, 2, 3, 4, 5}
{3, 4, 5}
# Adds multiple items from a list or a tuple, or a string or set itself.

s1 = {"Python", "Java", "C++"}
s1.update(["C", "Basic"])    # updating list
s1.update(("Ruby", "PHP"))     # updating tuple
s1.update({1})        # updating set
s1.update({"abc"})    # updating string

print (s1)

[out: ]
{1, 'Java', 'Ruby', 'PHP', 'C++', 'abc', 'C', 'Python', 'Basic'}

  • all() :: Return True if all elements of the set are true (or if the set is empty).
s1 = {1,2,3}
s2 = {0,1,2,3}
s3 = {False}
s4 = {}

print (all(s1))   # Does not contain 0 or False
print (all(s2))   # 0 is False
print (all(s3))   # False is False
print (all(s4))

[out: ]
True
False
False
True
  • any() :: Return True if any element of the set is true. If the set is empty, return False.
s1 = {1,2,3}
s2 = {}
s3 = {0}

print (any(s1))
print (any(s2))
print (any(s3))

[out: ]
True
False
False
  • enumerate() :: Return an enumerate object. It contains the index and value of all the items of set as a pair.
s1 = {"a","b"}

for idx, val in enumerate(s1):
    print("index is %d and value is %s" % (idx, val))

[out: ]
index is 0 and value is b
index is 1 and value is a
  • len() :: Return the length (the number of items) in the set.
s1 = {1,2,3}
print (len(s1))

[out: ]
3
  • max() :: Return the largest item in the set.
s1 = {1,2,3}  # Same type of data
print (max(s1))

[out: ]
3
s1 = {"a","b","c"}  # Same type of data

print (max(s1))

[out: ]
c
  • min() :: Return the smallest item in the set.
s1 = {1,2,3}  # Same type of data
print (min(s1))

[out: ]
1
s1 = {"a","b","c"}  # Same type of data
print (min(s1))

[out: ]
a
  • sorted() :: Return a new sorted list from elements in the set (does not sort the set itself).
s1 = {1,3,2}  # Same type of data
print (sorted(s1))

[out: ]
[1, 2, 3]
s1 = {"b","B","A","a"}  # Same type of data
print (sorted(s1))

[out: ]
['A', 'B', 'a', 'b']
  • sum() :: Retrun the sum of all elements in the set.
s1 = {1,3,2}  # Only int values
print (sum(s1))

[out: ]
6

FIND THE WHOLE CODE ON GITHUB:

https://github.com/parsispresswala/Prasik-s-Blogs/blob/master/Basic%20Python/08%20-%20Sets%20in%20Python.ipynb