A 'Set' is a Collection that can also hold multiple values. And in the 'Set', the elements are unordered, unindexed and doesn't allow duplicate values.
The declaration of a 'Set' is quite simple. You can place the multiple values inside braces '{ }' and Python will understand it is of type 'Set'.
x = {5, "John", "Python"} print(x)
So, in the above code we have created a 'Set' using square braces '{ }'.
And put an Integer type value (i.e. 5) and two String type values (i.e. 'John' and 'Python')
And initialised to the variable 'x'.
So, we can see that two different data types are assigned to a 'Set'. Also the values are not inserted in the same order.
i.e. We have created the Set with first element as '5', then 'John' and finally 'Python'.
But it is stored in somewhat different order.
i.e. The first element is 'Python', then '5' and finally 'John'.
And in the next line we have printed the 'Set' using the print statement.
Now, if we see the output,
So, this time the first element is 'Python', then '5' and finally 'John'. It might be different the next time you try printing it.
This is because a 'Set' doesn't maintain its order. The values in the 'Set' will not be inserted in the same order.
x = {5, "John", "Python"} for i in x: print(i)
Similarly, in the above code we have created a 'Set' using braces '{ }'.
And initialised to the variable 'x'.
As said earlier, the order is not maintained in Python. So, the above values are jumbled up.
In the next line we have used the 'for loop' to Iterate through the 'Set'.
for i in x: print(i)
Now, if we see the iterations of for loop,
In the first Iteration the first value of the 'Set' 'x' (i.e. 'Python') is taken and put into the variable 'i'.
And the print statement, prints the value of 'i'.
Similarly, in the second Iteration the second value of the 'Set' 'x' (i.e. 'John') is taken and put into the variable 'i'.
And the print statement, prints the value of 'i'.
Similarly, in the third Iteration the third value of the 'Set' 'x' (i.e. '5') is taken and put into the variable 'i'.
And the print statement, prints the value of 'i'.
Now, if you see the final output. You can find that the values of the 'Set' are not displayed in the same way they were inserted.
i.e. First 'Python' is printed, then the name 'John' and finally '5' is printed.
And if you see the Set,
It is not printed in the same order it was inserted. And this is why a Set is said to be 'UnOrdered'.
Next, let us see, how to access the elements of the Set.