Python Sets


set is a collection which is unordered, unindexed, and does not allow duplicate values.

Sets are written with curly brackets {}.


🔹 Create a Set

fruits = {"apple", "banana", "cherry"}
print(fruits)

🔹 No Duplicates

Sets automatically remove duplicates.

fruits = {"apple", "banana", "apple"}
print(fruits)  # {'apple', 'banana'}

🔹 Check if Item Exists

if "banana" in fruits:
    print("Yes")

🔹 Add Items

fruits.add("orange")

🔹 Add Multiple Items

fruits.update(["grape", "melon"])

🔹 Get Length

print(len(fruits))

🔹 Remove Items

fruits.remove("banana")   # Raises error if not found
fruits.discard("apple")   # No error if not found

🔹 Loop Through a Set

for x in fruits:
    print(x)

🔹 Join Sets

a = {"a", "b"}
b = {1, 2}
c = a.union(b)

🔹 Set Operations

x = {1, 2, 3}
y = {3, 4, 5}

print(x.intersection(y))  # {3}
print(x.difference(y))    # {1, 2}
print(x.symmetric_difference(y))  # {1, 2, 4, 5}

🧪 Try It Yourself

Practice adding, removing, checking membership, and performing operations like union and intersection.


Practice Questions

Q1. Write a Python program to create a set of 3 programming languages and print it.

Q2. Write a Python program to add "Java" to the set using add().

Q3. Write a Python program to add multiple items like "C" and "C++" to the set using update().

Q4. Write a Python program to remove "Python" from the set using remove() or discard().

Q5. Write a Python program to check if "JavaScript" exists in the set using the in keyword.

Q6. Write a Python program to create two sets and perform a union operation using union() or |.

Q7. Write a Python program to find common items between two sets using intersection().

Q8. Write a Python program to find the difference between two sets using difference().

Q9. Write a Python program to loop through a set and print each item using a for loop.

Q10. Write a Python program to get the number of items in a set using the len() function.


Go Back Top