β Programming Basics β Part 6: Sets ππ§
β
What is a Set?
A set is a collection of unique, unordered elements. It doesnβt allow duplicates.
β How to Create a Set
π Python
fruits = {"apple", "banana", "cherry"}π Java
Set<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");β Properties of Sets
βοΈ No duplicate values
βοΈ No guaranteed order
βοΈ Fast membership tests (in, contains)
β Add Elements
π Python: fruits.add("mango")
π Java: fruits.add("mango");
β Remove Elements
π Python: fruits.remove("banana")
π Java: fruits.remove("banana");
β Check Membership
π Python: "apple" in fruits
π Java: fruits.contains("apple")
β Loop Through a Set
π Python:
for fruit in fruits:
print(fruit)π Java:
for(String fruit : fruits) {
System.out.println(fruit);
}β Why Use Sets?
- Eliminate duplicates from data
- Fast checks for existence
- Efficient in set operations (union, intersection)
β Real-World Uses of Sets
- Store unique tags or categories
- Track visited pages
- Remove duplicates from a list
- Fast user lookup in access control systoperations fast!*