0% found this document useful (0 votes)
4 views2 pages

Python Set Methods and Operations Guide

Uploaded by

archanavisu02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Python Set Methods and Operations Guide

Uploaded by

archanavisu02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Set Functions, Methods & Operations with

Examples

add(): Adds an element.


my_set = {1, 2}
my_set.add(3)
print(my_set) # {1, 2, 3}

update(): Adds multiple elements.


my_set = {1}
my_set.update([2, 3])
print(my_set) # {1, 2, 3}

remove(): Removes element (error if not found).


my_set = {1, 2}
my_set.remove(2)
print(my_set) # {1}

discard(): Removes element (no error if not found).


my_set = {1, 2}
my_set.discard(3)
print(my_set) # {1, 2}

pop(): Removes random element.


my_set = {1, 2, 3}
my_set.pop()
print(my_set) # Random element removed

clear(): Removes all elements.


my_set = {1, 2}
my_set.clear()
print(my_set) # set()

union() (|): Combines sets.


a = {1, 2}
b = {2, 3}
print([Link](b)) # {1, 2, 3}
print(a | b) # {1, 2, 3}

intersection() (&): Common elements.


a = {1, 2}
b = {2, 3}
print([Link](b)) # {2}
print(a & b) # {2}

difference() (-): Elements in first, not second.


a = {1, 2, 3}
b = {2, 3}
print([Link](b)) # {1}
print(a - b) # {1}

symmetric_difference() (^): Elements in either but not both.


a = {1, 2}
b = {2, 3}
print(a.symmetric_difference(b)) # {1, 3}
print(a ^ b) # {1, 3}

len(): Number of elements.


print(len({1, 2, 3})) # 3

max(): Largest element.


print(max({1, 5, 3})) # 5

min(): Smallest element.


print(min({1, 5, 3})) # 1

sum(): Sum of elements.


print(sum({1, 2, 3})) # 6

You might also like