Python Set difference() Method

Returns a set containing the differences between two sets. If you have two sets, a and b, a.difference(b) returns all the items in a that are not in b.

Syntax

Python
set.difference(otherSet)

Parameters

ParameterDescription
otherSet Required. The set to compare with the current set.

Example

Python
desktopComponents = {'memory', 'processor', 'hard drive'}
laptopComponents = {'memory', 'processor', 'SSD', 'camera', 'keyboard'}

notInDesktop = laptopComponents.difference(desktopComponents)
notInLaptop  = desktopComponents.difference(laptopComponents)

print(f'Components only in the laptop computer: {notInDesktop}')
print(f'Components only in the desktop computer: {notInLaptop}')

Output

Components only in the laptop computer: {'keyboard', 'SSD', 'camera'}
Components only in the desktop computer: {'hard drive'}