English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python collection difference() usage and example

Méthodes de collection en Python

The different() method returns the set difference of two sets.

If A and B are two sets. The set difference of A and B is a set of elements that exist only in set A and not in set B, for example:

If
A = {1, 2, 3, 4}
B = {2, 3, 9}
Then,
A - B = {1, 4}
B - A = {9}

The syntax of the difference() method in Python is:

A.difference(B)

Here, A and B are two set collections. The following syntax is equivalent to A-B.

difference() return value

The difference() method returns the difference between two sets, which is also a set. It does not modify the original set.

Example1How does the difference() function work in Python?

A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
# Is equivalent to-B
print(A.difference(B))
# Is equivalent to-A
print(B.difference(A))

When running the program, the output is:

{'b', 'a', 'd'}
{'g', 'f'}

You can also use in Python - the operator to find the set difference.

Example2Use-The operator finds the set difference.

A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print(A-B)
print(B-A)

When running the program, the output is:

{'b', 'd', 'a'}
{'f', 'g'}

Méthodes de collection en Python