A Set in Python is a collection of unique elements. It does not allow duplicate values, and it is unordered.
We create a set using curly braces {} or the set() function.
- Example of Set:
numbers = {10, 20, 30, 40, 10}
print(numbers)
Output:
{10, 20, 30, 40}
Here, 10 appears only once because sets do not allow duplicate values:
- Important Characteristics of Set
- Does not allow duplicate values.
- Unordered collection.
- Mutable (we can add or remove elements).
- Does not support indexing.
Can store different data types.
Set Methods:
numbers = {10, 20, 30}
numbers.add(40)
numbers.remove(20)
numbers.discard(50)
print(numbers)
Output:
{10, 30, 40}
Top comments (0)