English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Méthodes de collection en Python
The Python set union() method returns a new set that contains all different elements from all sets.
The union of two or more sets is the set of all different elements that exist in all sets. For example:
A = {1, 2} B = {2, 3, 4} C = {5} Then, A ∪ B = B ∪ A = {1, 2, 3, 4} A ∪ C = C ∪ A = {1, 2, 5} B ∪ C = C ∪ B = {2, 3, 4, 5} A ∪ B ∪ C = {1, 2, 3, 4, 5}
The syntax of union() is:
A.union(*other_sets)
Note: *is not part of the syntax. It is used to indicate that this method can accept 0 or more parameters.
The union() method returns a new set that contains all elements from the set and all other sets (passed as parameters).
If no parameters are passed to union(), it returns a shallow copy of the set.
A = {'a', 'c', 'd'} B = {'c', 'd', 2 } C = {1, 2, 3} print('A.union() =
Output result
A U B = {2, 'a', 'd', 'c' B U C = {1, 2, 3, 'd', 'c' A U B U C = {1, 2, 3, 'a', 'd', 'c' A.union() = {'a', 'd', 'c'}
You can also use the | operator to find the union of sets.
A = {'a', 'c', 'd'} B = {'c', 'd', 2 } C = {1, 2, 3} print('A U B =', A | B) print('B U C =', B | C) print('A U B U C =', A | B | C)
Output result
A U B = {2, 'a', 'c', 'd' B U C = {1, 2, 3, 'c', 'd'} A U B U C = {1, 2, 3, 'a', 'c', 'd'