![]() |
| Python Sets tutorial explaining unordered property, no duplicate values, add() and update() methods with examples. |
A Set in Python is like a set of cards in a card pack. It is unordered, does not allow duplicate values, and is mutable (can change) ✅.
📌 Creating a Set
sports = {"tennis", "cricket", "football"}
print(sports)
print(type(sports))
Output example:
{'cricket', 'tennis', 'football'}
The order may change because sets are unordered.
🚫 No Indexing
Sets cannot be accessed using index numbers. Because they are unordered, there is no position number.
📏 Length of a Set
print(len(sports))
len() function returns the number of items in the set.
📦 Different Data Types
Sets can store different data types.
mixed_set = {"apple", 10, True}
🔄 Mutable Property
Sets are mutable ➜ That means you can add or update items.
➕ add() Method
add() is used to add a single element.
fruits = {"apple", "banana", "orange"}
fruits.add("grapes")
print(fruits)
Output example:
{'apple', 'orange', 'grapes', 'banana'}
🔗 update() Method
update() is used to combine two sets.
fruits = {"apple", "banana", "orange"}
animals = {"dog", "cat"}
fruits.update(animals)
print(fruits)
Output example:
{'apple', 'dog', 'cat', 'banana', 'orange'}
🎯 Sets are useful when you want unique values only and do not care about order. They are commonly used in Data Science and filtering duplicate data 🚀.
