Sets in Python | Union of 2 Sets in Python

# Sets in Python

0 1799

In python, the set can be considered as any sequence containing unique unordered values and all immutable objects that can never be changed. In other words, we can say that it does not permit modification. Identical to mathematics sets, in python also we can perform multiple operations such as slicing, intersection, difference, addition, discarding, removing, clear and coping

The syntax of sets is not much different from the list and tuple only they are enclosed with curly braces. We can also say that syntax of sets is only the list of objects enclosed with curly braces and separated by a comma that is written below.

Syntax with example
language = {"c", "java", "c++"}
print(language)

Output
{'java', 'c++', 'c'}
Sets does not allow repetition. If we have by mistake double time any elements in set it will display it will still display it one time. It is explained with the help of example given below.
language = {"c", "java", "c++", "c++"}
print(language)

Example
{'c++', 'c', 'java'}
Now let us perform various operations on the set.

Example
language = {"c", "java", "c++", "c++"}
print(language)

Output
{'java', 'c'}

Union of two sets in python
language = {"c", "java", "c++", "c++"}
language1 = {"hindi", "english", "tamil", "punjabi"}
print(language|language1)

Output
{'tamil', 'hindi', 'english', 'java', 'punjabi', 'c', 'c++'}

Difference of two sets
language = {"c", "java", "c++", "c++"}
language1 = {"hindi", "english", "tamil", "punjabi"}
print(language-language1)

Output
{'c++', 'c', 'java'}

Symetric differences of two set
language = {"c", "java", "c++", "c++"}
language1 = {"hindi", "english", "tamil", "punjabi"}
print(language^language1)

Output
{'java', 'c++', 'c', 'punjabi', 'tamil', 'hindi', 'english'}

Check the element in set
language = {"c", "java", "c++"}
#print(language)
#for x in language:
#print(x)
print("c" in language)

Output
True

Conversion of list into set in python
language = ["c", "java", "c++", "c++"]
listconverted=set(language)
print(listconverted)

Output
{'c', 'c++', 'java'}

Share: