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
Copy Code
set.difference(otherSet)
Parameters
Parameter | Description |
---|---|
otherSet |
Required. The set to compare with the current set. |
Example
Python
Copy Code
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'}