Python has a built-in method called set. set type has the following characteristics
Sets are a collection which is unordered and unindexed
Set elements are unique. Duplicate elements are not allowed.
A set itself may be mutable, but the elements within a set is immutable.
You can create sets in two ways:
using set method followed by a parenthesis ().
using curly brackets{}.
set()
You can have an ITERABLE object such as list or tuple within set(<iter>). This returns the list or tuple as a set wrapped in a curly bracket {}. Any iterable object can be converted to a set using set(). You can think of set() as extend() method of lists.
A list within set().
numbers =set([1, 2, 3, 4, 5, 6, 7])print(numbers)
{1,2,3,4,5,6,7}
A tuple within set().
numbers =set((1, 2, 3, 4, 5, 6, 7))print(numbers)
{1,2,3,4,5,6,7}
A string with a set().
my_letters =set('ABCDEF')print(my_letters)
{'E','F','C','B','A','D'}
While converting an iterable objects to a set, the returned set is deduplicated.
# Example 1my_cities =set(['Krakow', 'Warsaw', 'Warsaw', 'Kielce'])print(my_cities)# Example 2my_letters =set('AaBBCCDDEEE')print(my_letters)# Example 3my_numbers =set('12345342')print(my_numbers)
# Example 1 output{'Krakow','Kielce','Warsaw'}# Example 2 output{'D','E','B','C','a','A'}# Example 3 output{'4','1','3','2','5'}
You can see that the output are unordered and deduplicated. The original orders are not kept. set() only accepts an object that is iterable such as a string, list or tuple. For example, integers are not iterable and it raises an error, to be specific TypeError, while we try to create a set with integer.
You can create a set using curly brackets{}. Curly brackets{} must have only IMMUTABLE objects. Each element has to separated by a comma, similar to lists and tuples, in other words, a set can be created as {<obj1>, <obj2>, <obj3>, ......, <objn>}.
# Example 1my_cities ={'Krakow','Warsaw','Warsaw','Kielce'}print(my_cities)# Example 2my_letters ={'AaBBCCDDEEE'}print(my_letters)# Example 3my_numbers ={12345342}print(my_numbers)
# Example 1 output{'Kielce','Warsaw','Krakow'}# Example 2 output{'AaBBCCDDEEE'}# Example 3 output{12345342}
As you can see, the curly brackets do not iterate through iterable elements. Each object is present in the set intact regardless of iterability.
Empty set
set can also be empty, as we had empty list and empty tuple. You can create an empty set using built-in function of set() only because Python interprets empty curly brackets {} as an empty dictionary.
# set function{False,1.858,34,3.2,True,'cat','Name'}# Curly brackets{False,1.858,34,3.2,True,'cat','Name'}
How to add element(s) to a set?
Sets are unordered and changing with indexing brackets is not possible. Sets are mutable, but we cannot perform slicing or indexing operations to access its elements. Python raises TypeError when you use indexing or slicing operation.
You can delete an element from a set using discard() or remove().
remove function
remove() will delete the element where it is present and raises a KeyError where the element is absent.
# Element is presentnew_set ={9,8,7,6}new_set.remove(8)print(new_set)# Element is absentnew_set ={9,8,7,6}new_set.remove(5)print(new_set)
# Element is present# print(new_set){9,6,7}# Element is absent# print(new_set)KeyErrorTraceback (most recent call last)<ipython-input-23-25ec930c2723>in<module>()1 new_set ={9,8,7,6}2---->3 new_set.remove(5)45print(new_set)KeyError:5
discard function
You can also use discard() to delete an element. if element is a member of the set, then removes it, but it does nothing when element is not a member of a set.
# Element is presentnew_set ={9,8,7,6}new_set.discard(8)print(new_set)# Element is absentnew_set ={9,8,7,6}new_set.discard(5)print(new_set)
# Element is present# print(new_set){9,6,7}# Element is absent# print(new_set){8,9,6,7}
pop function
You can use pop() on a set. pop() returns an arbitrary element because sets are unordered.
| operator creates a union of two sets (both side have to be sets), otherwise, it raises an error. While union() takes an iterable and converts it to a set before performing union operation. See example below; notice that the second set is a tuple.
You can use difference() method or- operatorto get intersect of two sets. The difference of set A and set B is a set of elements that are only present in set A but not set B. The difference of set B and set A is vice versa.
All set methods and operators above support multiple set union, intersection, difference and symmetric difference when you are using methods and operators except symmetric difference method.