A Set is a collection used to store multiple items in a single variable. Sets are unordered, do not allow duplicate values, and are mutable (can be changed after creation).
Creating a Set
Example
fruits = {"apple", "banana", "mango"}
print(fruits)
Output:
{'apple', 'banana', 'mango'}
Duplicate Values Not Allowed
Example
fruits = {"apple", "banana", "apple", "mango"}
print(fruits)
Output:
{'apple', 'banana', 'mango'}
Set Length
Example
fruits = {"apple", "banana", "mango"}
print(len(fruits))
Output:
3
Access Set Items
Sets do not support indexing. You can access items using a loop.
Example
fruits = {"apple", "banana", "mango"}
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
The order may vary.
Check if Item Exists
Example
fruits = {"apple", "banana", "mango"}
print("banana" in fruits)
Output:
True
Add Items to a Set
Example
fruits = {"apple", "banana"}
fruits.add("mango")
print(fruits)
Output:
{'apple', 'banana', 'mango'}
Remove Items from a Set
Example
fruits = {"apple", "banana", "mango"}
fruits.remove("banana")
print(fruits)
Output:
{'apple', 'mango'}
Set with Different Data Types
Example
data = {"Python", 25, True, 5.5}
print(data)
Output:
{'Python', 25, True, 5.5}
Convert List to Set
Example
numbers = [1, 2, 2, 3, 4, 4]
unique_numbers = set(numbers)
print(unique_numbers)
Output:
{1, 2, 3, 4}
Summary
- Sets store unique values only.
- Duplicate values are automatically removed.
- Sets are unordered and do not support indexing.
- Items can be added using
add(). - Items can be removed using
remove(). - Sets are useful when you need unique data.
- Sets can store different data types.