Python Sets

In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements.
The order of elements in a set is undefined though it may consist of various elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
A set is a collection which is unordered, unchangeable*, and unindexed.
Example:

set_a = {1, 2, "3", 4}
print(set_a)
print(type(set_a))
Creating a Set

Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a ‘comma’.
A set contains only unique elements but at the time of set creation, multiple duplicate values can also be passed.
Order of elements in a set is undefined and is unchangeable.
Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.
Example:

set1 = set()
print(set1)
set1 = set("aabbccddeeff")
print(set1)
set1 = set("1112234563456654234")
print(set1)
Note – A set cannot have mutable elements like a list or dictionary, as it is mutable.
Adding elements to a Set

Elements can be added to the Set by using the built-in add() function.
Only one element at a time can be added to the set by using add() method, loops are used to add multiple elements at a time with the use of add() method.
Example:

x = set()
print(x)
x.add(1)
x.add(2)
x.add(3)
print(x)
string = "rguktwebrguktweb"
for i in string:
    x.add(i)
print(x)

Note: Lists cannot be added to a set as elements because Lists are not hashable whereas Tuples can be added because tuples are immutable and hence Hashable.
For the addition of two or more elements Update() method is used. The update() method accepts lists, strings, tuples as well as other sets as its arguments. In all of these cases, duplicate elements are avoided.
Example:

x = set([1,2,3,4])
print(x)
x.update(["abbcdfa"])
print(x)
x.update([(1,2),5,6])
print(x)
Accessing elements of a Set

Set items cannot be accessed by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
Example:

x = ([1,456,54,21,43])
for i in x:
    print(i,end=" ")
print(1 in x)
Remove Set Elements

Elements can be removed from the Set by using the built-in remove() function but a KeyError arises if the element doesn’t exist in the set.
To remove elements from a set without KeyError, use discard(), if the element doesn’t exist in the set, it remains unchanged.
Example:

sett = {"hello","world","python","rguktweb"}
print(sett)
sett.remove("hello")
print(sett)
sett.update("world")
print(sett)

Note: If the item to remove does not exist, discard() will NOT raise an error.