Python Sets
Sets
The Python data type set is an unordered collection with no duplicate elements. The elements inside the set are separated by commas.
Examples
Extract values from a set
>>> my_set = {1, 2, 3, 8, 12} >>> my_set {8, 1, 2, 3, 12} >>> a = {'test', 1, 'aaa', 4} >>> print(a) {1, 4, 'test', 'aaa'} >>>
Eliminate duplicate elements
>>> x = {1, 2, 1, 3, 3, 4, 8, 8, 5} >>> print(x) {1, 2, 3, 4, 5, 8} >>> y = {'test','a','test','b','b',7,8,7,'c'} >>> print(y) {'b','test',7,8,'a','c'} >>>
Check for element
>>> my_set = {'green', 3, 'red', '7'} >>> print(my_set) {'7', 3, 'green', 'red'} >>> 'red' in my_set True >>> 'blue' in my_set False >>> 3 in my_set True >>> '7' in my_set True >>>