This article brings you a simple explanation of set collections in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The set collection uses {} to save a set of iterable objects, such as lists, strings, and the set collection itself. If there are duplicate elements in the set, the duplicate elements will be automatically removed
a=set([1,2,3]) print(a) b=set('hello python') print(b) c=set({1,2,3}) print(c) d=set({'hello python'}) print(type({'hello '})) print(d)
Display results
{1, 2, 3} {'h', 'l', 'e', ' ', 'p', 'n', 'y', 'o', 't'} {1, 2, 3} <class 'set'> {'hello python'}
add | After adding an element to the set collection, replace the original object | a.add( 4) print(a) output {1, 2, 3, 4} |
remove | After removing an element from the set collection, replace the original object. If If the replaced element is not in the set collection, an error will be reported |
a.remove(2) print(a) output {1,3} |
Little knowledge points: set collection can be seen as It is a mathematically unordered and non-repeating set of elements, so the intersection and union in the mathematical sense can be done between the two sets
Output result{1,3} | |
Output result{1,2,3,4} |
The above is the detailed content of A brief explanation of set collections in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!