How to Use Set difference() Method in PythonPython Basics


The difference() method returns a new set which consists of the difference between two sets.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

Country1= {"Ulaanbaatar","Pakistan","China", "India", "Japan","Mongolia","North Korea","South Korea"}
Country2 = {"China", "India", "Japan","Mongolia"}
Country3= Country1.difference(Country2)

print(Country1)
print(Country2)
print(Country3)

Output:

{'Pakistan', 'China', 'South Korea', 'Japan', 'India', 'Mongolia', 'North Korea', 'Ulaanbaatar'}
{'India', 'China', 'Japan', 'Mongolia'}
{'Pakistan', 'North Korea', 'Ulaanbaatar', 'South Korea'}

Syntax

x.difference(y)

Parameters

The parameter is the set to check for differences in two sets.

Return Value

It returns the difference between two sets which is also a set.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us