0% found this document useful (0 votes)
0 views

Set_python

This document provides an overview of Python sets, which are collections of unique elements that cannot contain duplicates. It explains how to create sets, add or remove items, and perform various operations such as union, intersection, and difference. Additionally, it highlights the use of built-in functions and methods to manipulate sets effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Set_python

This document provides an overview of Python sets, which are collections of unique elements that cannot contain duplicates. It explains how to create sets, add or remove items, and perform various operations such as union, intersection, and difference. Additionally, it highlights the use of built-in functions and methods to manipulate sets effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Python Sets

A set is a collection of unique data, meaning that elements within a set


cannot be duplicated.

For instance, if we need to store information about student IDs, a set is


suitable since student IDs cannot have duplicates.

Create a Set in Python


In Python, we create sets by placing all the elements inside curly braces
{}, separated by commas.
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 mutable
elements like lists, sets or dictionaries as its elements.
Let's see an example,
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type


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

# create a set of mixed data types


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

In the above example, we have created different types of sets by


placing all the elements inside the curly braces {}.

Note: When you run this code, you might get output in a different
order. This is because the set has no particular order.

Create an Empty Set in Python


Creating an empty set is a bit tricky. Empty curly braces {} will make an
empty dictionary in Python.
To make a set without any elements, we use the set() function without
any argument. For 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))
Here,
empty_set - an empty set created using set()
empty_dictionary - an empty dictionary created using {}
Finally, we have used the type() function to know which class
empty_set and empty_dictionary belong to.

Duplicate Items in a Set


Let's see what will happen if we try to include duplicate items in a set.
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Here, we can see there are no duplicate items in the set as a set cannot
contain duplicates.

Add and Update Set Items in Python


Sets are mutable. However, since they are unordered, indexing has no
meaning.
We cannot access or change an element of a set using indexing or
slicing. The set data type does not support it.

Add Items to a Set in Python


In Python, we use the add() method to add an item to a set. For
example,
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
# using add() method
numbers.add(32)
print('Updated Set:', numbers)
Update Python Set
The update() method is used to update the set with items other
collection types (lists, tuples, sets, etc). For example,

companies = {'Lacoste', 'Ralph Lauren'}

tech_companies = ['apple', 'google', 'apple']

# using update() method

companies.update(tech_companies)

print(companies)

# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Here, all the unique elements of tech_companies are added to the


companies set.

Remove an Element from a Set


We use the discard() method to remove the specified element from a
set. For example,

languages = {'Swift', 'Java', 'Python'}

print('Initial Set:',languages)

# remove 'Java' from a set

removedValue = languages.discard('Java')

print('Set after remove():', languages)

Here, we have used the discard() method to remove 'Java' from the
languages set.
Built-in Functions with Set
Here are some of the popular built-in functions that allow us to perform
different operations on a set.

Iterate Over a Set in Python


fruits = {"Apple", "Peach", "Mango"}

# for loop to access each fruits


for fruit in fruits:
print(fruit)

Find Number of Set Elements


We can use the len() method to find the number of elements present in
a Set. For example,
even_numbers = {2,4,6,8}
print('Set:',even_numbers)

# find number of elements


print('Total Elements:', len(even_numbers))
Here, we have used the len() method to find the number of elements
present in a Set.

Python Set Operations


Python Set provides different built-in methods to perform mathematical
set operations like union, intersection, subtraction, and symmetric
difference.
Union of Two Sets
The union of two sets A and B includes all the elements of sets A and B.
We use the | operator or the union() method to perform the set union
operation. For 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))
Note: A|B and union() is equivalent to A ⋃ B set operation.

Set Intersection
The intersection of two sets A and B include the common elements
between set A and B.
In Python, we use the & operator or the intersection() method to
perform the set intersection operation. For 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))
Note: A&B and intersection() is equivalent to A ⋂ B set operation.

Difference between Two Sets


The difference between two sets A and B include elements of set A that
are not present on set B
We use the - operator or the difference() method to perform the
difference between two sets. For 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))
Note: A - B and A.difference(B) is equivalent to A - B set operation.

You might also like