Sets
A Set is an unordered collection of data types that is iterable, mutable, unindexed 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.
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 cannot have mutable elements like a list or dictionary, as it is mutable.
Example:
# Creation of Set in Python
set1 = set()
print("Initial blank Set: ")
print(set1)
# Creating a Set with the use of a String
set1 = set("Libed")
set2 = {"P","Y","T","H","O","N"}
print("\nSet with the use of String: ")
print(set1)
print(type(set1))
print(set2)
print(type(set2))
# Creating a Set with the use of Constructor
String = 'Libed'
set1 = set(String)
print("\nSet with the use of an Object: ")
print(set1)
# Creating a Set with the use of a List
set1 = set(["Libed", "Python", "Tutorial"])
print("\nSet with the use of List: ")
print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'B', 'E', 'D', 'I', 'L'}
<class 'set'>
{'P', 'Y', 'T', 'H', 'O', 'N'}
<class 'set'>
Set with the use of an Object:
{'I', 'L', 'E', 'B', 'D'}
Set with the use of List:
{'Python', 'Tutorial', 'Libed'}
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. A set can be created with another method as follows:
Example:
# Creating a Set with a List of Numbers
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])
print("\nSet with the use of Numbers: ", set1)
# Creating a Set with a mixed type of values
set1 = set([1, 2, 'Libed', 4, 'Python', 6, 'Python'])
print("\nSet with the use of Mixed Values", set1)
# Another Method to create sets in Python
my_set = {1, 2, 3}
print("\n", my_set)
Output:
Set with the use of Numbers: {1, 2, 3, 4, 5, 6}
Set with the use of Mixed Values {'Libed', 1, 2, 4, 6, 'Python'}
{1, 2, 3}