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))
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)
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)
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)
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
Example:
x = ([1 ,456 ,54 ,21 ,43 ])
for i in x:
print (i,end =" " )
print (1 in x)
Elements can be removed from the Set by using the built-in
To remove elements from a set without KeyError, use
Example:
sett = {"hello" ,"world" ,"python" ,"rguktweb" }
print (sett)
sett.remove ("hello" )
print (sett)
sett.update ("world" )
print (sett)