In this tutorial , we learn about python set() function. Python set() function is nothing but it creates a set object. The elements in a set list are unordered so that it will be appear in random order. It is used to store multiple items in a single variable. A set is a collection which is unordered ,unindexed and unchangeable. It do not allow duplicate values.
Set items can be of any data type ,it can be with strings, integers and boolean values.
Note :
Set items are unchangeable, but you can remove items and new items.
Functions of python set() function
Unordered :
Unordered means that items in a set do not have defined order .
Unchangeable :
Once a set is created , you cannot change its items, but you can remove items and add new items.
Example of set :
thisset = { "kiwi", "apple", "papaya" } print(thisset)
Output :
{ 'kiwi', 'apple', 'banana' }
Explanation :
In this we can observe that the provided values are represented in the output as the given values.
To get the length of a set :
To get the count or length of items , we use len() function.
Example :
thisset = {"mango", "orange", "grapes"} print(len(thisset)
Output :
3
Explanation :
In this example ,we can observe that count of items is represented in the output. So it counts the elements in a set.
Example of different data types :
set1 = {"abc", 34, True, 40, "male}
Output :
{ True, 34, 40, 'male', 'abc' }
Explanation :
In this we can observe that different data types are represented in the output. Like integers, strings and boolean values.
Duplicates Not Allowed
Example :
thisset = { "apple", "kiwi", "cherry", "apple" } print(thisset)
Output :
{ 'apple', 'kiwi', cherry' }
Explanation :
In this example, we can observe duplicates are not allowed to represent in the output, only once it is appeared.