-
Hajipur, Bihar, 844101
A set is a collection which is unordered, unindexed, and does not allow duplicate values.
Sets are written with curly brackets {}
.
fruits = {"apple", "banana", "cherry"}
print(fruits)
Sets automatically remove duplicates.
fruits = {"apple", "banana", "apple"}
print(fruits) # {'apple', 'banana'}
if "banana" in fruits:
print("Yes")
fruits.add("orange")
fruits.update(["grape", "melon"])
print(len(fruits))
fruits.remove("banana") # Raises error if not found
fruits.discard("apple") # No error if not found
for x in fruits:
print(x)
a = {"a", "b"}
b = {1, 2}
c = a.union(b)
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}
Practice adding, removing, checking membership, and performing operations like union and intersection.
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.
Q1: What is a set in Python?
Q2: Which symbol defines a set?
Q3: Can a set contain duplicate values?
Q4: Which method adds one item to a set?
Q5: Which method adds multiple items to a set?
Q6: What does discard() do if the item doesn’t exist?
Q7: Which operation returns only items common in both sets?
Q8: What is the result of set1.union(set2)?
Q9: What is the output of len(set)?
Q10: Are sets mutable (can be changed)?