You are on page 1of 8

What is a set

1. Sets are used to store multiple items in a single variable.


2. A Set in Python programming is an unordered collection data type
3. Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
4. Set are represented by { } (values enclosed in curly braces)
5. The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on a
data structure known as a hash table. Since sets are unordered, we cannot access items
using indexes as we do in lists.

Creating and initializing a set

1. In Python, we create sets by placing all the elements inside curly braces {}, separated by
comma.
2. A set can have any number of items and they may be of different types (integer, float,
tuple, string etc.).
3. Note: A set cannot have mutable elements like lists, sets or dictionaries as its elements.
4. Example:

a) # create a set of integer type


student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

b) # create a set of string type


vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)

c) # create a set of mixed data types


mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)

Creating an empty set

1. Creating an empty set is a bit tricky. Empty curly braces {} will make an empty
dictionary in Python.

2. To make a set without any elements, we use the set() function without any argument.

3. Example:
# create an empty set
empty_set = set()
# create an empty dictionary
empty_dictionary = { }

# check data type of empty_set


print('Data type of empty_set:', type(empty_set))

# check data type of dictionary_set


print('Data type of empty_dictionary', type(empty_dictionary))

Adding values in set

1. use the method add() to add a value to a set.

2. Example:
a = set()
a.add(1)
a.add(2)
a.add(3)
a.add(2)
a.add('hello')
print(a)

3. But this function can add a single element. If you want to add iterable elements like list
or set, you can do so by using update() function as shown below:

a.update([1,2,4,'hello','world']) #list as iterable element


a.update({1,2,5}) #set as iterable element
print(a)

Removing values from set

1. There are two functions to remove elements from Python Set. One is remove() and
another is discard() function.
2. If the element you are trying to remove is not in the set, the remove() function will raise
exception for this. But the discard function will not do anything like this.
3. Example for discard method:
a = {1,2,3,4,5,6}
#remove 3 using discard() function
a.discard(3)
print(a)
#call discard() function again to remove 3
a.discard(3) #This won't raise any exception
print(a)

4. Example for remove method:


#call remove() function to remove 5
a.remove(5)
print(a)
#call remove() function to remove 5 again
a.remove(5) #this would raise exception
print(a) #this won't be printed

Iterating through a set

1. Like many standard python data types, it is possible to iterate through a set. This can be
done using For loop
2. Example:
subject = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}
for i in subject:
print(i)

3. If you look at the output of printing each of the values, notice that the values printed in
the set are not in the order they were added in. This is because sets are unordered.
4. Transform a Python Set into Ordered Values: If you find that you need to get the
values from your set in an ordered form, you can use the sorted function, which outputs a
list that is ordered.
5. Example of sorted method:
a. Ascending order:

subject = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}


print(sorted(subject, reverse = True))

b. Descending order:

subject = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}


print(sorted(subject, reverse = True))

Note: The reverse parameter is set to True, which means the list will be sorted in descending
order. If reverse is not specified or set to False, the list will be sorted in ascending order.

Set membership test

1. Python’s in and not in operators allow you to quickly determine if a given value is or
isn’t part of a collection of values. This type of check is common in programming, and
it’s generally known as a membership test in Python.
2. Membership tests check whether a specific element is contained in a sequence, such as
strings, lists, tuples, or sets.
3. Example for in operator :
a = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS', 'Java', 'Spark', 'Scala'}
# Membership test
print('Python' in a)#returns true
print('python' in a)#returns false
4. Example for not in operator
a = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS', 'Java', 'Spark', 'Scala'}
# Membership test
print('GIT' not in a)
print('SAS' not in a)

Methods of set

Python has a set of built-in methods that you can use on sets.

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two
or more sets
difference_update() Removes the items in this set that are also included in
another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more
sets
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two
sets
symmetric_difference_update() inserts the symmetric differences from this set and
another
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable

Python Set Operations


A common use of sets in Python is computing standard math operations such as union,
intersection, difference, and symmetric difference.
The image below shows a couple standard math operations on two sets A and B. The red part
of each Venn diagram is the resulting set of a given set operation.
Union operation

1. The union of two sets A and B include all the elements of set A and B.
2. Visual Representation

3. We use the | operator or the union() method to perform the set union operation.
4. Example:
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
# perform union operation using |
print('Union using |:', A | B)
# perform union operation using union()
print('Union using union():', A.union(B))

Set Intersection
1. The intersection of two sets A and B include the common elements between set A and B.
2. Visual Representation

3. In Python, we use the & operator or the intersection() method to perform the set
intersection operation.
4. Example
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
# perform intersection operation using &
print('Intersection using &:', A & B)
# perform intersection operation using intersection()
print('Intersection using intersection():', A.intersection(B))

Difference between Two Sets


1) The difference between two sets A and B include elements of set A that are not present
on set B.
2) Visual Representation

3) We use the - operator or the difference() method to perform the difference between two
sets.
4) Example

# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference operation using &
print('Difference using &:', A - B)
# perform difference operation using difference()
print('Difference using difference():', A.difference(B))

Set Symmetric Difference


1. The symmetric difference between two sets A and B includes all elements of A and B
without the common elements.
2. Visual Representation
3. In Python, we use the ^ operator or the symmetric_difference() method to perform
symmetric difference between two sets.
4. Example

# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference operation using &
print('using ^:', A ^ B)
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))

You might also like