Set Datatype

  • Duplicate values are not allowed
  • A Set is an unordered collection element where each element is unique.

    The properties of Set Datatype are :

    • Order is not preserved
    Indexing and slicing concepts are not applicable
  • Heterogeneous objects are allowed
  • Mutable
  • Set is represented by using curly braces with comma separation.
  • We can perform union, intersection and difference operations can be performed on the set elements.
  • Here we cannot create an empty set, if we try to create an empty set, by default it will be considered as dictionary datatype because when compared to set and dictionary, the dictionary datatype is most commonly used datatype and hence the priority has been given to the dictionary data type.
  • We can create an empty set by using the set() function.
  • We can add an element to the set by using the method called add.
  • The syntax to add an element to the set is:
      set=s.add(10)
    set=s.add("A")
    set=s.add("water")​
  • The difference between List and Set
    List Set
    Duplicate elements are allowed Duplicate elements are not allowed
    Insertion order is preserved Insertion order is not preserved
    The list is represented by the square brackets The Set is represented by the curly braces
    Indexing and slicing concepts are applicable Indexing and slicing concepts are not applicable

    Python Bytes and Bytearray

Different Ways of Creating Set Objects

We can create a set by using different ways as follow:

Creating an empty set:

We can create an empty set as shown below

new_set=set()
Creating a Set by using available elements:
set={10,20,30,40}
Creating set by using the set() function:
List=[30,60,90]
New_set=set(List)
print(New_set)
Creating a set object by using Range function:
s=set(range(0,101,10))
print(s)
Creating a set with dynamic input:
s=eval(input("Enter set of values:"))
print(s)

creating-a-set-by-using-eval-function

creating a set by converting string to set:
string=set("Apple")
print(string)

Python Datatype Summary

Concatenation Operation on Set

Python does not support concatenation operation on set. If we try to perform concatenation operation on the elements of the set, then we will get a type error.

set1={11,23,45}
set2={23,45,11}
set3=set1+set2
print(set3)

The output is:

concatenation-does-not-support-set

Repetition Operation on Set

Python does not support repetition operation on set. If we try to perform repetition operation on the elements of the set, then we will get a type error.

set1={11,23,45}
set2={23,45,11}
set3=set1*set2
print(set3)

The output is:

repetition-operation-on-set

None Datatype

Equality Operator for Set

We can compare the elements of the two sets by using the equality operator.

The operators which are used to compare the Set elements are

  • Equal to(==)
  • Not equal(!=)

Python Returns True when

  • The number of Elements of the two sets must be the same.
  • The content of elements including the case must be the same.
  • Insertion order is not preserved
    set1={11,23,45,'Cat'}
    set2={'Cat',23,45,11}
    print(set1==set2)
    print(set2!=set1)​

    The output is:

    equality-operator-for-set

Python Comments

Relational Operator for Set

The relational operator compares the first element of the set and returns True or False depending on the conditions given. As the set does not support insertion order and hence the relational operator does not make much sense even they are applicable on set
The Relational Operators are:

  • Less Than
  • Greater Than
  • Less Than or Equal to
  • Greater Than or Equal to
set1={13,14,15,16,17}
set2={19,17,13,14,1516}
print(set1>set2)
print(set1<set2)
print(set1>=set2)
print(set1<=set2)

The output is:

relational-operator-on-set

Python Constants

Membership Operator for Set

Python supports to check whether the given character or a string is a member of any Set or not by using the in and not in operators.

The following example demonstrates the membership operator

set={28,32,47,56}
print(47 in set)
print(65 not in set)

The output is:

membership-operator-for-set

Methods and Functions of Set Datatype

Python supports some of the Methods and Functions to use with Set Datatype

Function on Set:

The len() function supports the set data type and returns the total number of elements present in the given set.

The syntax for the len() function is

set={23,33,43,53,63}
print(len(set))

The output is:

len-function-on-set

Methods on Set:

The add() method is used to add an element to the set

The syntax for the add() method is

set={23,33,43,53,63}
set.add(50)
print(set)

The output is:

adding-an-element-to-the-set

The update() method is used to add multiple elements to the set. We can pass any number of arguments by using the update() method, but all the arguments should be iterable like string, tuple, list.

The syntax for the update() method is:

set={20,30,40}
list=[50,60]
set.update(list)
print(set)
set.update(range(1,6),'mango')
print(set)

The output is:

using-update-method-on-set

The Difference Between add() method and update() method

Add() Update()
We can use add() method to add an individual element to the set We can use update() method to add multiple elements to the set
In the case of the add() method, we can pass only one argument In case of update() method, we can pass any number of arguments, but all the arguments should be iterable

The remove() method is used to remove the specified element present in the given set. if the specified element is not present in the given set, then python will throw a key error.

The syntax for the remove() method is

s.remove(x) ##x is a specofied element present in the given set

Example:

set={6,12,18,24,30}
data=set.remove(24)
print(set)

The output is:

removing-element-from-the-set

If we try to remove an element which is not present in the given set, then the output is:

set={6,12,18,24,30}
data=set.remove(55)
print(set)

removing-element-from-the-set-which-is-not-present-in-the-given-set

The discard() method is used to remove an element from the given set if the specified element is not present in the given set then the discard() method will just ignore it.

The syntax for the discard() method is

s.discard(x) ## x is a specified element present in the set

Example:

set={3,6,9,2,15,18,21}
info=set.discard(18)
print(set)

The output is:

discarding-an-element-in-the-set

If we try to remove an element which is not present in the given set, then discard() method will not throw any key error, instead, it will just print the current elements present in the set.

set={3,6,9,2,15,18,21}
info=set.discard(33)
print(set)

discarding-an-element-not-present-in-the-set

The pop() method is used to remove an element from the given set, but pop() method removes elements randomly.

The syntax for the pop() method is

s.pop(x) ##  x is an element present in the set

Example:

set={4,8,12,16,20,24}
info=set.pop()
print(info)

The output is:

pop-method-on-set

The pop() method is going to remove elements randomly

set={4,8,12,16,20,24}
print(set.pop())
print(set.pop())
print(set.pop())
print(set.pop())
print(set.pop())
print(set.pop())

The output is:

removing-element-randomly

If we apply pop() method on an empty set, then python will throw a key error.

applying-pop-method-on-emoty-set

The clear() method is used to remove all the elements from the given set.

The syntax for the clear() method is

s.clear()

Example:

set={12,24,36,48,60}
info=set.clear()
print(set)

The output is:

clear-method-for-set

The list of set methods:

Method Description
Python Set remove() Removes Element from the Set
Python Set add() adds an element to a set
Python Set copy() Returns Shallow Copy of a Set
Python Set clear() remove all elements from a set
Python Set difference() Returns Difference of Two Sets
Python Set difference_update() Updates Calling Set With Intersection of Sets
Python Set discard() Removes an Element from The Set
Python Set intersection() Returns Intersection of Two or More Sets
Python Set intersection_update() Updates Calling Set With Intersection of Sets
Python Set isdisjoint() Checks Disjoint Sets
Python Set issubset() Checks if a Set is Subset of Another Set
Python Set issuperset() Checks if a Set is Superset of Another Set
Python Set pop() Removes an Arbitrary Element
Python Set symmetric_difference() Returns Symmetric Difference
Python Set symmetric_difference_update() Updates Set With Symmetric Difference
Python Set union() Returns Union of Sets
Python Set update() Add Elements to The Set.
Python any() Checks if any Element of an Iterable is True
Python all() returns true when all elements in iterable is true
Python ascii() Returns String Containing Printable Representation
Python bool() Converts a Value to Boolean
Python enumerate() Returns an Enumerate Object
Python filter() constructs iterator from elements which are true
Python frozenset() returns immutable frozenset object
Python iter() returns iterator for an object
Python len() Returns Length of an Object
Python max() returns largest element
Python min() returns smallest element
Python map() Applies Function and Returns a List
Python set() returns a Python set
Python sorted() returns sorted list from a given iterable
Python sum() Add items of an Iterable
Python zip() Returns an Iterator of Tuples

Performing Mathematical Operations by using Set Specific Methods

Python provides some set specific methods to perform mathematical operations on the set elements.

The set specific methods are:

  • Union()
  • Difference()
  • Intersection()
  • Symmetric difference()

The Union() method combines the all the elements present in the given setsand creats a new set.

The syntax for the union() method is

set=A|B ##Where A,B are the two sets

Example:

set1={5,10,15,20}
set2={6,12,18,24}
set3=set1|set2
print(set3)

The output is:

union-operation-on-set

We can also use set3=set1.union(set2), then also we will get the same output

set1={5,10,15,20}
set2={6,12,18,24}
set3=set1.union(set2)
print(set3)

The output is:

Using-union-method

The Intersection() method creates a new set by selecting the common elements from the given sets

The syntax for the intersection() method is

set3=set1.intersection(set2) or set1&set2

Example:

set1={7,14,21,28,35}
set2=[8,28,35,90}
set3=set1.intersection(set2)
print(setset3)

The output is:

intersection-of-sets

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions