Set is a major topic in mathematics. It plays an important role in mathematics.
In mathematics it is defined as a group of unique data items of similar type & it does not allow duplicated elements in the group.
In Python, Set is defined as an unordered collection of unique elements.
Let's start with creation and UNION operations on Set.
Note : union() is a predefined method.
"""
created_at : 14 Feb 2017.
updated_at : 14 Feb 2017.
aim of script : To understand the concept of set/frozenset in Python.
coded by : Rishikesh Agrawani.
Python version : 2.7.12
"""
#Interactive mode programming - union operation on sets
>>> s1 = set()
>>> print s1
set([])
>>>
>>> evens = [0,2,4,6,8,10]
>>> evens_set = set(evens)
>>> print evens_set
set([0, 2, 4, 6, 8, 10])
>>>
>>> odds = [1,3,5,7,9]
>>> odds_set = set(odds)
>>> print odds_set
set([1, 3, 9, 5, 7])
>>>
>>> evens_odds_set = evens_set|odds_set
>>> print evens_odds_set
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>>
>>> s3 = evens_set.union(odds_set)
>>> print s3
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>>
>>> A = set([1,2,3,4,5])
>>> B = set((4,5,6,7,8))
>>> C = set({7:"seven",9:"nine",10:"ten"})
>>> print A
set([1, 2, 3, 4, 5])
>>>
>>> print B
set([8, 4, 5, 6, 7])
>>>
>>> print C
set([9, 10, 7])
>>>
>>> print A|B
set([1, 2, 3, 4, 5, 6, 7, 8])
>>>
>>> print A|C
set([1, 2, 3, 4, 5, 7, 9, 10])
>>>
>>> print B|C
set([4, 5, 6, 7, 8, 9, 10])
>>>
>>> print A.union(B)
set([1, 2, 3, 4, 5, 6, 7, 8])
>>>
>>> print A.union(C)
set([1, 2, 3, 4, 5, 7, 9, 10])
>>>
>>> print B.union(C)
set([4, 5, 6, 7, 8, 9, 10])
>>>
>>> print B.uinion(C)
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'set' object has no attribute 'uinion'
>>>
Now we are little bit familiar with UNION operations on Set.
So let's see INTERSECTION operations on Set.
Note : intersection() is a predefined method.
#Interactive mode programming - intersection operation on sets
>>> wholes = [0,1,2,3,4,5,6,7,8] >>> evens = (0,2,4,6) >>> odds = {1:"one", 3:'three', 5:'five', 7:'seven'} >>> >>> print wholes [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> >>> print evens (0, 2, 4, 6) >>> >>> print odds {1: 'one', 3: 'three', 5: 'five', 7: 'seven'} >>> >>> S1 = set(wholes) >>> S2 = set(evens) >>> S3 = set(odds) >>> >>> print S1 set([0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> >>> print S2 set([0, 2, 4, 6]) >>> >>> print S3 set([1, 3, 5, 7]) >>> >>> S1&S2 set([0, 2, 4, 6]) >>> >>> S1&S3 set([1, 3, 5, 7]) >>> >>> S2&S3 set([]) >>> >>> S1.intersection(S2) set([0, 2, 4, 6]) >>> >>> S1.intersection(S3) set([1, 3, 5, 7]) >>> >>> S2.intersection(S3) set([]) >>>