General

Python Sets

General July 19, 2019
Python Sets

Python Sets

What is a set?

A set is an unordered collection of items in which every element is unique, iterable and immutable (cannot be modified). However, the set as a whole is mutable. There are no duplicate elements in a set and you can add or even delete items in it. Sets can be helps to perform mathematical operations like intersection ,union, symmetric difference and so on. A set can consist of elements or items with different immutable data types like integer, string, float, tuple, etc. However, a set cannot have mutable elements like lists, dictionaries or a set itself.

Defining a set in Python

A set has a list of items that are enclosed within curly brackets and separated by commas. However, if you an older version of Python, you may have to use the set keyword. The set keyword works in the later versions of Python as well. The example below shows two sets (months and mixed_set) of defined elements with the same data type as well as with different data types respectively. The output shows a random order of the elements within the set. Thus, a set is an unordered collection of items.

Example

months = {"Jan","Feb","Mar"}
days = set(["Mon","Tue","Wed"]) #using set keyword
mixed_set = {(1, 2, 3), "Good Morning", 32.0}
print(months)
print(days)
print(mixed_set)

Output

{'Feb', 'Mar', 'Jan'}
{'Tue', 'Mon', 'Wed'}
{32.0 , (1, 2, 3), "Good Morning"}

Accessing items in a set

A set element cannot be referenced by an index number since it is unordered. However, the items in a set can be looped through by using a for loop. You can also choose to access a particular item in a set by using the “in” keyword. However, note that it is case sensitive.

Using for loop

fruits_set = {"mango", "banana", "orange"}
for x in fruits_set:
print(x)

Output

banana
cherry
apple

Using “in” keyword

fruits_set = {"mango", "banana", "orange"}
print("orange" in fruits_set)
print("Orange" in fruits_set)

Output

True

False

Click Here -> Get Python 100% Practical Training

Adding more items in a set

You can add more items in a set by using the add() method. Since a set does not use indexing, you need to specify the exact value within the method parenthesis.

Example

flower_set = {"tulip", "geranium", "orchid"}
flower_set.add("anthurium")
print(flower_set)

Output

{'tulip', 'orchid', 'geranium', 'anthurium'}

Removing items from a set

You can remove an item from a set by using the discard() method. Since there is no index attached to an item in a set, you would need to specifically address the value within the method parenthesis.

Example

flower_set = {"tulip", "geranium", "orchid"}
flower_set.discard("tulip")
print(flower_set)

Output

{'orchid', 'geranium'}

Clearing all items in a set

You can remove all items in a set by using the clear() method.

Example

flower_set = {"tulip", "geranium", "orchid"}
flower_set.clear()
print(flower_set)

Output

set()

Click Here-> Become a Python Certified Experts in 25 Hours 

Copying a set

Example

An existing set can be copied to a new set by using the copy() method.
flower_set = {"tulip", "geranium", "orchid"}
new_flower_set = flower_set.copy()
print("new set: ", new_flower_set) 

Output

new set:  {'orchid', 'tulip', 'geranium'}

Sorting a set

The values in a set can be sorted in ascending or descending order using the sorted() method. By passing the set variable inside the sorted()  parameter, the items in a set will be printed in ascending order by default. The sorted() method takes in three parameter-iterable, key and reverse. The iterable parameter is required in which you need to specify the variable name of the set. The key and reverse parameter is optional. You can use the reverse parameter to sort the items in ascending order (reverse = False) or descending order (reverse = True).

Example

vowel_set = {"e", "a", "u", "o", "i"}
print("Default sort: ", sorted(vowel_set))
print("Ascending order: ",sorted(vowel_set,reverse=False))
print("Descending order: ", sorted(vowel_set, reverse=True))

Output

Default sort:  ['a', 'e', 'i', 'o', 'u']
Ascending order:  ['a', 'e', 'i', 'o', 'u']
Descending order:  ['u', 'o', 'i', 'e', 'a']

Updating a set

You can update a set by adding elements from one set to another set. You can use the update() method to do this. In the example below, set A is updated by adding all the elements of set B in set A. Common elements between the two sets are updated as one element. In this case, both set A and set B have 1 as a common element so when set A is updated, it is not repeated.

Example

A = {'a', 'b', 1}
B = {1, 2, 3}
print('A =',A)
print('B =',B)
result = A.update(B)
print('Update A =',A)

Output

A = {'b', 'a', 1}
B = {1, 2, 3}
Update A = {1, 2, 'b', 3, 'a'}

Union of sets

The union operation (Set1 | Set2) can be used to compare two sets and produce a new set that contains distinct elements from both the sets. For instance, if there are more than two occurrences of the same element in both the sets, the new set would produce the element only once so there would be no repetition of elements. In the example below, “Wed” can be found in both days1 and day2 so when using the union operation, it would produce “Wed” only once as shown in the output. You can either use the union operator | or union() method in this case. The union() method is similar to the update() method. However, by using the union() method, the results are produced in a new set rather than updating an existing set.

Example

days1 = {"Mon","Tue","Wed"}
days2 = {"Wed","Thu","Fri","Sat","Sun"}
days = days1|days2
print(days)
days = days1.union(days2)
print(days)

Output

{'Sat', 'Thu', 'Wed', 'Sun', 'Tue', 'Mon', 'Fri'}
{'Sat', 'Thu', 'Wed', 'Sun', 'Tue', 'Mon', 'Fri'}

Click Here-> Python Interview Questions and Answers

Intersection of sets

The intersection operation (Set1 & Set2) can be used to compare two sets in which only the common elements between the sets will be produced in a new set. In the following example, since “Wed” is common both sets, the new set “days” will return “Wed” as the output. You can either use the & operator or intersection() method in this case.

Example

days1 = {"Mon","Tue","Wed"}
days2 = {"Wed","Thu","Fri","Sat","Sun"}
commonDays1 = days1 & days2
print(commonDays1)
commonDays2 = days1.intersection(days2)
print(commonDays2)

Output

{'Wed'}
{'Wed'}

Updating intersection of sets

While the intersection of two sets is produced in a new set by using intersection(), an intersection_update() method is used to update an existing set.

Example

days1 = {"Mon","Tue","Wed"}

days2 = {"Wed","Thu","Fri","Sat","Sun"}

day1 = days1.intersection_update(days2)

print(day1)

Output

{‘Wed’}

Difference of sets

The difference operation (Set1 – Set2) can be used to compare two sets where the elements found only in one set will be produced in a new set. This means that common elements found between two sets are not produced in the new set. You can either use the – operator or difference() method in this case.

If we look at the following example, ColorA – ColorB produces a set where the unique elements in ColorA are produced. Likewise, ColorB – ColorA produces a set where the unique elements of Color B are produced. Moreover, common elements are not added to any of the new sets, ColorAB and ColorBA.

Example

ColorA = {"Red","Green","Blue","Yellow"}
ColorB = {"Orange","Pink","Purple","Green","Yellow"}
ColorsAB = ColorA - ColorB
ColorsBA = ColorB.difference(ColorA)
print("ColorA - ColorB: ", ColorsAB)
print("ColorB - ColorA: ", ColorsBA)

Output

ColorA - ColorB:  {'Blue', 'Red'}
ColorB - ColorA:  {'Purple', 'Orange', 'Pink'}

Updating difference of sets

While the difference of two sets is produced in a new set by using the difference() method, difference_update() method is used to update the difference in an existing set. In the example below, ColorA is updated by keeping the unique elements that are unique to ColorA which is red and blue. It removes those elements that are common to another set in comparison (in this case, ColorB). Hence, since green and yellow are also found in ColorB, it is removed from ColorA.

Example

ColorA = {"Red","Green","Blue","Yellow"}
ColorB = {"Orange","Pink","Purple","Green","Yellow"}
print("Color A: ", ColorA)
print("Color B: ", ColorB)
ColorA.difference_update(ColorB)
print("Color A: ", ColorA)

Output

Color A:  {'Green', 'Yellow', 'Blue', 'Red'}
Color B:  {'Green', 'Pink', 'Orange', 'Purple', 'Yellow'}
Color A:  {'Red', 'Blue'}

Subsets and supersets

You can use the <= operator or issubset() method to check if a set is a subset of another set. If it is, it would return True else it would return False. Similarly, you can use the >= operator or issuperset() methodto check if a set is a superset of another set.

Example

Employees = {"Max","Teresa","Josh","Terrance","Beth" }
Helpdesk_Employees = {"Teresa", "Josh"}
Subset = Helpdesk_Employees <= Employees
Superset = Employees >= Helpdesk_Employees
print(Subset)
print(Superset)
Subset = Helpdesk_Employees.issubset(Employees)
Superset = Employees.issuperset(Helpdesk_Employees)
print(Subset)
print(Superset)

Output

True
True
True
True

Symmetric difference of sets

You can find the unique elements between two sets by using the symmetric_difference() method. In the example below, the output elements are all unique and cannot be found in another set.

Example

set_A = {1, 2, 3, 4, 5}
set_B = {6, 7, 8, 1, 2}
print(set_A.symmetric_difference(set_B))
print(set_B.symmetric_difference(set_A))

Output

{3, 4, 5, 6, 7, 8}

{3, 4, 5, 6, 7, 8}

Updating symmetric difference of sets

An existing set is updated by storing all the elements that are unique between the existing set and the set which is being compared (set_B in this case).

Example

set_A = {1, 2, 3, 4, 5}
set_B = {6, 7, 8, 1, 2}
print(set_A.symmetric_difference_update(set_B))
print(set_A)

Output

{3, 4, 5, 6, 7, 8}

Click Here-> Get Python Training with Real-time Projects

Besant Technologies – Chennai & Bangalore Branch Locations

Besant Technologies - Velachery Branch

Plot No. 119, No.8, 11th Main road, Vijaya nagar,

Velachery, Chennai - 600 042

Tamil Nadu, India

Landmark - Reliance Digital Opposite Street

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Tambaram Branch

No.2A, 1st Floor, Duraisami Reddy Street,

West Tambaram, Chennai - 600 045

Tamil Nadu, India

Landmark - Near By Passport Seva

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - OMR Branch

No. 5/318, 2nd Floor, Sri Sowdeswari Nagar,

OMR, Okkiyam Thoraipakkam, Chennai - 600 097

Tamil Nadu, India

Landmark - Behind Okkiyampet Bus Stop,

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Porur Branch

No. 180/84, 1st Floor, Karnataka Bank Building,

Trunk Road, Porur, Chennai - 600 116

Tamil Nadu, India

Landmark - Opposite to Gopalakrishna Theatre

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Anna Nagar Branch

Plot No:1371, 28th street kambar colony,

I Block, Anna Nagar, Chennai - 600 040

Tamil Nadu, India

Landmark - Behind Reliance Fresh

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - T.Nagar Branch

Old No:146/2- New No: 48,

Habibullah Road,T.Nagar, Chennai - 600 017

Tamil Nadu, India

Landmark - Opposite to SGS Sabha

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Thiruvanmiyur Branch

22/67, 1st Floor, North mada street, Kamaraj Nagar

Thiruvanmiyur, Chennai 600041

Tamil Nadu, India

Landmark - Above Thiruvanmiyur ICICI Bank

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Siruseri Branch

No. 4/76, Ambedkar Street, OMR Road, Egatoor, Navallur,

Siruseri, Chennai 600130

Tamil Nadu, India

Landmark - Near Navallur Toll Gate, Next to Yamaha Showroom

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - Maraimalai Nagar Branch

No.37, Ground Floor, Thiruvalluvar Salai,

Maraimalai Nagar,Chennai 603209

Tamil Nadu, India

Landmark - Near to Maraimalai Nagar Arch

  +91-8099 770 770

  info@besanttechnologies.com

Besant Technologies - BTM Layout Branch

No 2, Ground floor, 29th Main Road,

Kuvempu Nagar,BTM Layout 2nd Coming from Silkboard,

AXA company signal, Stage, Bangalore - 560 076

Karnataka, India

Landmark - Next to OI Play School

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Marathahalli Branch

No. 43/2, 2nd Floor, VMR Arcade,

Varthur Main Road, Silver Springs Layout,

Munnekollal, Marathahalli, Bengaluru - 560037

Karnataka, India

Landmark - Near Kundalahalli Gate Signal

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Rajaji Nagar Branch

No. 309/43, JRS Ecstasy, First Floor,

59th Cross, 3rd Block, Bashyam Circle,

Rajaji Nagar, Bangalore - 560 010

Karnataka, India

Landmark - Near Bashyam Circle

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Jaya Nagar Branch

No. 2nd Floor,1575,11th Main Road,

4th T-Block, Pattabhirama Nagar,

Jaya Nagar, Bangalore - 560 041

Karnataka, India

Landmark - Opposite to Shanthi Nursing Home

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Kalyan Nagar Branch

No.513, 4th Cross Rd

2nd Block, HRBR Layout,

Kalyan Nagar, Bangalore - 560 043

Karnataka, India

Landmark - Opposite to kalayan nagar Axis Bank

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Electronic City Branch

No. 7, 3rd Floor, Ganga Enclave,

Neeladri Road, Karuna Nagar, Doddathoguru Village,

Electronics City Phase 1, Electronic City,

Bangalore - 560100, karnataka, India

Landmark - Adjacent to HDFC Bank and State Bank Of India

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Indira Nagar Branch

No.54, 1st Floor,

5th Main kodihalli,

Bengaluru, Karnataka 560008, India

Landmark - Behind Leela Palace Hotel,

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - HSR Layout Branch

Plot No. 2799 & 2800, 27th Main,

1st Sector, HSR Layout,

Bengaluru, Karnataka 560102, India

  +91-8767 260 270

  info@besanttechnologies.com

Besant Technologies - Hebbal Branch

No.29, 2nd Floor, SN Complex,

14th Main Road, E-Block Extention, Sahakara Nagar,

Bengaluru, Karnataka -560092, India

  +91-8767 260 270

  info@besanttechnologies.com

Scroll Up