In Python, a set is a data type that stores multiple elements of the same or different data types. The main difference between a set and a list in Python is a list is ordered and it allows duplicate elements. But, a set is unordered and it does not allow duplicate elements. So, if we want to store some elements in a data type such that later we can test the membership of an element or eliminate duplicate entries, then we should use a set instead of a list. Moreover, a set supports operations like union, difference, intersection, and symmetric difference, but a list does not.
Let’s first look into how to create a set and print its elements. In Python, we can create a set and print its elements in the following way:
s = {1, 2, 3, 4} print(s)
The output will be:
{1, 2, 3, 4}
As we discussed, a set is unordered. So, we cannot refer to an element in a set using an index. Instead, we can use the membership operator “in” to check whether an element is present in a set.
s = {1, 2, 3, 4} if 2 in s: print("2 is a member of s")
The output of the above program will be:
2 is a member of s
Please also note that a set does not allow duplicate entries. So, if we define a set like s = {1, 2, 3, 4, 4} and try to print …






0 Comments