/    /  Python – Sets

Python – Sets:

In this tutorial, we will learn about sets in python. A set is a datatype which holds an unordered collection with immutable and no duplicate elements.

By the name, Set can be used for various mathematical operations. Mathematical operation may be union, intersection or difference, etc. Let us see the example of using the Set below.


>> set1={'html','c','java','python','sql'}

>> print(set1)

{'c', 'python', 'sql', 'html', 'java'}

# Below we have given duplicates

>>> set1={'html','c','java','python','sql','java'}

# we can observe that duplicates are ignored

>>> print(set1)

{'c', 'python', 'java', 'html', 'sql'}

>>> set1

{'c', 'python', 'java', 'html', 'sql'}

Membership testing in Sets:

>> set1={'html','java','python','sql','java'}

>>> set1
{'python', 'java', 'html', 'sql'}

>>> print(set1)
{'python', 'java', 'html', 'sql'}

>>> 'c' in set1

>>> 'java' in set1

Sets Operations in Python:

>>> set1={'html','java','python','sql','java'}

>>> set2={'html','oracle','ruby'}
# Unique words in set1

>>> set1

{'python', 'java', 'html', 'sql'}

>>> set2

{'ruby', 'html', 'oracle'}

# words in set1 but not in set2

>>> set1-set2

{'python', 'java', 'sql'}

# Words in set1 or set2 or both

>>> set1|set2

{'ruby', 'html', 'oracle', 'python', 'java', 'sql'}

# Words in both set1 and set2

>>> set1&set2


# Words in set1 or set2 but not both

>>> set1^set2

{'oracle', 'python', 'sql', 'ruby', 'java'}