Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Sets

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Sets in Python

A Set in Python programming is an unordered collection data type that is iterable, mutable and has
no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
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.
Example of Python Sets
 Python3

var = {"Geeks", "for", "Geeks"}

type(var)

Output:
set
Time Complexity: O(1)
Auxiliary Space: O(1)

Type Casting with Python Set method

The Python set() method is used for type casting.

 Python3

# typecasting list to set

myset = set(["a", "b", "c"])

print(myset)

# Adding element to the set

myset.add("d")

print(myset)

Output:
Python set is an unordered datatype, which means we cannot know in which order the elements of
the set are stored.
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Check unique and Immutable with Python Set

Python sets cannot have a duplicate value and once it is created we cannot change its value.

 Python3

# Python program to demonstrate that

# a set cannot have duplicate values

# and we cannot change its items

# a set cannot have duplicate values

myset = {"Geeks", "for", "Geeks"}

print(myset)

# values of a set cannot be changed

myset[1] = "Hello"

print(myset)

Output:
The first code explains that the set cannot have a duplicate value. Every item in it is a unique
value.
The second code generates an error because we cannot assign or change a value once the set is
created. We can only add or delete items in the set.
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment
Heterogeneous Element with Python Set

Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string,
integer, boolean, etc datatypes.

 Python3

# Python example demonstrate that a set

# can store heterogeneous elements

myset = {"Geeks", "for", 10, 52.7, True}

print(myset)

Output:
{True, 10, 'Geeks', 52.7, 'for'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Python Frozen Sets


Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. It can be done
with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the same
after creation.
If no parameters are passed, it returns an empty frozenset.

 Python

# Python program to demonstrate differences

# between normal and frozen set

# Same as {"a", "b","c"}

normal_set = set(["a", "b","c"])


print("Normal Set")

print(normal_set)

# A frozen set

frozen_set = frozenset(["e", "f", "g"])

print("\nFrozen Set")

print(frozen_set)

# Uncommenting below line would cause error as

# we are trying to add element to a frozen set

# frozen_set.add("h")

Output:
Normal Set
{'a', 'c', 'b'}

Frozen Set
{'e', 'g', 'f'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Internal working of Set


This is based on a data structure known as a hash table. If Multiple values are present at the
same index position, then the value is appended to that index position, to form a Linked List.
In, Python Sets are implemented using a dictionary with dummy variables, where key beings the
members set with greater optimizations to the time complexity.
Set Implementation:
Sets with Numerous operations on a single HashTable:
Methods for Sets

Adding elements to Python Sets

Insertion in the set is done through the set.add() function, where an appropriate record value is
created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However,
in worst case it can become O(n).
 Python3

# A Python program to

# demonstrate adding elements

# in a set

# Creating a Set

people = {"Jay", "Idrish", "Archi"}

print("People:", end = " ")

print(people)

# This will add Daxit

# in the set

people.add("Daxit")

# Adding elements to the

# set using iterator

for i in range(1, 6):


people.add(i)

print("\nSet after adding element:", end = " ")

print(people)

Output:
People: {'Idrish', 'Archi', 'Jay'}

Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi',


'Jay', 'Daxit'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Union operation on Python Sets

Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements, at the
same time duplicates are removed. The Time Complexity of this is O(len(s1) + len(s2)) where s1
and s2 are two sets whose union needs to be done.
 Python3

# Python Program to

# demonstrate union of

# two sets

people = {"Jay", "Idrish", "Archil"}

vampires = {"Karan", "Arjun"}

dracula = {"Deepanshu", "Raju"}


# Union using union()

# function

population = people.union(vampires)

print("Union using union() function")

print(population)

# Union using "|"

# operator

population = people|dracula

print("\nUnion using '|' operator")

print(population)

Output:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}

Union using '|' operator


{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}
Time Complexity: O(n)
Auxiliary Space: O(n)

Intersection operation on Python Sets

This can be done through intersection() or & operator. Common Elements are selected. They are
similar to iteration over the Hash lists and combining the same values on both the Table. Time
Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to
be done.
 Python3

# Python program to

# demonstrate intersection

# of two sets

set1 = set()

set2 = set()

for i in range(5):

set1.add(i)

for i in range(3,9):

set2.add(i)

# Intersection using

# intersection() function

set3 = set1.intersection(set2)

print("Intersection using intersection() function")

print(set3)
# Intersection using

# "&" operator

set3 = set1 & set2

print("\nIntersection using '&' operator")

print(set3)

Output:
Intersection using intersection() function
{3, 4}

Intersection using '&' operator


{3, 4}
Time Complexity: O(n)
Auxiliary Space: O(n)

Finding Differences of Sets in Python

To find differences between sets. Similar to finding differences in the linked list. This is done
through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1))

 Python3

# Python program to

# demonstrate difference

# of two sets

set1 = set()

set2 = set()
for i in range(5):

set1.add(i)

for i in range(3,9):

set2.add(i)

# Difference of two sets

# using difference() function

set3 = set1.difference(set2)

print(" Difference of two sets using difference() function")

print(set3)

# Difference of two sets

# using '-' operator

set3 = set1 - set2

print("\nDifference of two sets using '-' operator")

print(set3)

Output:
Difference of two sets using difference() function
{0, 1, 2}

Difference of two sets using '-' operator


{0, 1, 2}
Time Complexity: O(n)
Auxiliary Space: O(n)

Clearing Python Sets

Set Clear() method empties the whole set inplace.

 Python3

# Python program to

# demonstrate clearing

# of set

set1 = {1,2,3,4,5,6}

print("Initial set")

print(set1)

# This method will remove

# all the elements of the set

set1.clear()

print("\nSet after using clear() function")


print(set1)

Output:
Initial set
{1, 2, 3, 4, 5, 6}

Set after using clear() function


set()
Time Complexity: O(n)
Auxiliary Space: O(n)
However, there are two major pitfalls in Python sets:
1. The set doesn’t maintain elements in any particular order.
2. Only instances of immutable types can be added to a Python set.
Time complexity of Sets
Operation Average case Worst Case notes

x in s O(1) O(n)

Union s|t O(len(s)+len(t))

replace “min”
O(min(len(s),
Intersection s&t O(len(s) * len(t)) with “max” if t is
len(t))
not a set

Multiple
(n-1)*O(l) where l is
intersection
max(len(s1),..,len(sn))
s1&s2&..&sn

Difference s-t O(len(s))

Operators for Sets


Sets and frozen sets support the following operators:
Operators Notes

key in s containment check

key not in s non-containment check

s1 == s2 s1 is equivalent to s2

s1 != s2 s1 is not equivalent to s2

s1 <= s2 s1 is subset of s2

s1 < s2 s1 is proper subset of s2

s1 >= s2 s1 is superset of s2

s1 > s2 s1 is proper superset of s2

s1 | s2 the union of s1 and s2

s1 & s2 the intersection of s1 and s2

s1 – s2 the set of elements in s1 but not s2

s1 ˆ s2 the set of elements in precisely one of s1 or s2

Python – Append Multiple elements in set


In Python, sets are an unordered and mutable collection of data type what does not contains any
duplicate elements. In this article, we will learn how to append multiple elements in the set at once.
Example:
Input: test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]
Output: {1, 2, 4, 5, 6, 7, 9, 10}
Explanation: All elements are updated and reordered. (5 at 3rd position).

Input: test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 8]


Output: {1, 2, 4, 5, 6, 7, 8, 9, 10}
Explanation: All elements are updated and reordered. (8 at 7th position).
Append Multiple Elements in Set in Python
There are various ways by which we can append elements given in a list to a Set in Python. They
are as follows:
Using update() Method
In this method, we will use Python‘s in-built set update() function to get all the elements in the list
aligned with the existing set.

# initializing set

test_set = {6, 4, 2, 7, 9}

# printing original set

print("The original set is : " + str(test_set))

# initializing adding elements

up_ele = [1, 5, 10]

# update() appends element in set

# internally reorders

test_set.update(up_ele)

# printing result
print("Set after adding elements : " + str(test_set))

Output:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Using | Operator (Pipe Operator)
The pipe operator internally calls the union() function, which can be used to perform the task of
updating the Python set with new elements.
 Python3

# initializing set

test_set = {6, 4, 2, 7, 9}

# printing original set

print("The original set is : " + str(test_set))

# initializing adding elements

up_ele = [1, 5, 10]

# | performing task of updating

test_set |= set(up_ele)

# printing result

print("Set after adding elements : " + str(test_set))

Output:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Using List Comprehension
Here, we will use the Python list comprehension method to append only those elements in a set
that are not already present in it. Then we use the set() constructor to convert the list to a Python
set.
 Python3

# initializing set

test_set = {6, 4, 2, 7, 9}

test_list = list(test_set)

# printing original list

print("The original set is : " + str(test_list))

# initializing adding elements

up_ele = [1, 5, 10]

# adding elements to list using list comprehension

test_list += [ele for ele in up_ele if ele not in test_list]

# printing result

print("Set after adding elements : " + str(set(test_list)))

#This code is contributed by Vinay Pinjala.

Output:
The original set is : [2, 4, 6, 7, 9]
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Using reduce() Method
This approach uses the reduce() function from the functools module to apply a union operation
between each element of a list and the set, resulting in a new set in Python. The reduce() function
takes a lambda function and the union() function
 Python3

# import functools

from functools import reduce

# initializing set

test_set = {6, 4, 2, 7, 9}

# printing original list

print("The original list is : " + str(test_set))

# initializing adding elements

up_ele = [1, 5, 10]

# using reduce and union function to append elements to set

result_set = reduce(lambda res, ele: res.union(set([ele])),


up_ele, test_set)

# printing result

print("Set after adding elements : " + str(result_set))

Output:
The original list is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}

Python Set | update()


Python update() function in set adds elements from a set (passed as an argument) to the set.
Syntax : set1.update(set2)
Here set1 is the set in which set2 will be added.
Parameters : Update() method takes any number of argument. The arguments can be a set, list,
tuples or a dictionary. It automatically converts into a set and adds to the set.

Return value : This method adds set2 to set1 and returns nothing.
Example of Python set update()

Example 1: Working with Python set update list

 Python3

# Python program to demonstrate the

# use of update() method

list1 = [1, 2, 3]

list2 = [5, 6, 7]

list3 = [10, 11, 12]

# Lists converted to sets

set1 = set(list2)

set2 = set(list1)

# Update method
set1.update(set2)

# Print the updated set

print(set1)

# List is passed as an parameter which

# gets automatically converted to a set

set1.update(list3)

print(set1)

Output :
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7, 10, 11, 12}

Example 2: Python set update element in set

 Python3

# Python program to demonstrate the

# use of update() method

list1 = [1, 2, 3, 4]

list2 = [1, 4, 2, 3, 5]

alphabet_set = {'a', 'b', 'c'}


# lists converted to sets

set1 = set(list2)

set2 = set(list1)

# Update method

set1.update(set2)

# Print the updated set

print(set1)

set1.update(alphabet_set)

print(set1)

Output :
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 'c', 'b', 'a'}

Example 3: Add elements of the dictionary to Set

 Python3

number = {1, 2, 3, 4, 5}

num_Dict = {6: 'Six', 7: 'Seven', 8: 'Eight',

9: 'Nine', 10: 'Ten'}


number.update(num_Dict)

print("Updated set: ", number)

Output:
Updated set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Python | Remove items from Set


In this article, we will try to a way in which the elements can be removed from the set in a
sequential manner. Before going into that let’s learn various characteristic of a set. A Set is an
unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s
set class represents the mathematical notion of a set. 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. Examples:
Input : set([12, 10, 13, 15, 8, 9])
Output :
{9, 10, 12, 13, 15}
{10, 12, 13, 15}
{12, 13, 15}
{13, 15}
{15}
set()

Input : set(['a','b','c','d','e'])
Output :
{'d', 'c', 'a', 'b'}
{'c', 'a', 'b'}
{'a', 'b'}
{'b'}
set()
Using the pop() method The pop() is an inbuilt method in Python that is used to pop out or
remove the elements one by one from the set. The element that is the smallest in the set is
removed first followed by removing elements in increasing order. In the following program, the
while loop goes onto removing the elements one by one, until the set is empty.

 Python3

# Python program to remove elements from set

# Using the pop() method

def Remove(initial_set):

while initial_set:

initial_set.pop()

print(initial_set)

# Driver Code

initial_set = set([12, 10, 13, 15, 8, 9])

Remove(initial_set)

Output:
{9, 10, 12, 13, 15}
{10, 12, 13, 15}
{12, 13, 15}
{13, 15}
{15}
set()

Using discard() method:

Approach:
This approach removes the elements from the set using the discard() method.
Initialize a set my_set with the given elements.
Enter a loop that runs as long as there are elements in the set my_set.
Find the maximum element in the set using the max() function and remove it from the set using the
discard() method.
Print the updated set after each removal.
Exit the loop when the set my_set becomes empty.

 Python3

# initialize the set

my_set = set([12, 10, 13, 15, 8, 9])

# remove elements one by one using discard() method

while my_set:

my_set.discard(max(my_set))

print(my_set)

Output

{8, 9, 10, 12, 13}


{8, 9, 10, 12}
{8, 9, 10}
{8, 9}
{8}
set()
The time complexity of the given code is O(n^2), where n is the size of the input set. This is
because for each element in the set, the max() function is called, which has a time complexity of
O(n). Since there are n elements in the set, the total time complexity becomes O(n^2).
The space complexity of the given code is O(n), where n is the size of the input set. This is
because a set of size n is initialized in memory, and the loop runs until all the elements are
removed from the set. Therefore, the maximum amount of memory used by the program is
proportional to the size of the input set.
Using remove() method:
Approach:
 Initialize set.
 Use for loop to iterate length of set times.
 Use the remove method on the first element of the set which is retrieved by the next() method
on iter() function.
 Python
# initialize the set

my_set = set([12, 10, 13, 15, 8, 9])

# remove elements one by one using remove() method

for i in range(len(my_set)):

my_set.remove(next(iter(my_set)))

print(my_set)

Output

set([9, 10, 12, 13, 15])


set([10, 12, 13, 15])
set([12, 13, 15])
set([13, 15])
set([15])
set([])
Time complexity: O(N) Here N is the length of the set and we are iterating over length of the set.
Space complexity: O(N) N is set lenght.

How to check if a set contains an element in


Python?
In this article, we will discuss how to check if a set contains an element in python.

Method: 1 Using in operator


This is an membership operator used to check whether the given value is present in set or not. It
will return True if the given element is present in set , otherwise False.
Syntax:
element in set
where
 set is an input set
 element is the value to be checked
Example: Check if an element is present in a set
 Python3

# import random module

import random

# create a set with integer elements

data = {7058, 7059, 7072, 7074, 7076}

# check 7058

print(7058 in data)

# check 7059

print(7059 in data)

# check 7071

print(7071 in data)

Output:
True
True
False
Method 2: Using not in operator
This is an membership operator used to check whether the given value is present in set or not. It
will return True if the given element is not present in set, otherwise False
Syntax:
element not in set
where,
 set is an input set
 element is the value to be checked
Example: Check if an element is present in a set
 Python3

# import random module

import random

# create a set with integer elements

data = {7058, 7059, 7072, 7074, 7076}

# check 7058

print(7058 not in data)

# check 7059

print(7059 not in data)

# check 7071

print(7071 not in data)

Output:
False
False
True
Method 3: Using Counter() Function
 Python3

from collections import Counter

# create a set with integer elements

data = {7058, 7059, 7072, 7074, 7076}

freq = Counter(data)

# check 7058

print(7058 in freq.keys())

# check 7059

print(7059 in freq.keys())

# check 7071

print(7071 in freq.keys())

Output

True
True
False
Time Complexity:O(N)
Auxiliary Space: O(N)

Method #4 : Using operator.countOf() method.


 Python3
import operator as op

# create a set with integer elements

data = {7058, 7059, 7072, 7074, 7076}

# check 7058

print(op.countOf(data, 7058) > 0)

# check 7059

print(op.countOf(data, 7059) > 0)

# check 7071

print(op.countOf(data, 7071) > 0)

Output

True
True
False
Time Complexity: O(n)
Auxiliary Space: O(1)

You might also like