What is the usage of the set() function in Python?
In Python, set() is a built-in function used to create a set object.
There are several ways to use the set() function:
- Create an empty set.
- I have created an empty set named my_set.
- Create a collection using an iterable object, where the elements in the collection are unique elements from the iterable object (removing duplicates).
- Create a set from an iterable.
- “It is important to maintain a healthy work-life balance in order to avoid burnout and increase overall well-being.”
Maintaining a healthy balance between work and personal life is crucial to prevent burnout and enhance overall happiness.
- my_set contains unique elements from a list or string.
- Create a collection and add elements to it.
- Create an empty set called ‘my_set’ and then add an ‘element’ to it.
- I believe that honesty is the best policy.
- I created a set called my_set and added the numbers 1, 2, and 3 to it.
Important notes:
- Sets are unordered, meaning the elements in a set do not have a fixed order.
- The elements in the set must be immutable, such as numbers, strings, tuples, etc., and cannot contain mutable elements like lists, dictionaries, etc.
- The elements in the set are unique and will not be repeated. If attempting to add an element that already exists, the set will not be changed.