Python Set Questions

Python Set Questions & Answers

Here are some common Python `set` interview questions with answers.

1. What is a Set in Python?

A set is an unordered collection of unique elements in Python.

            
# Creating a set
numbers = {1, 2, 3, 4, 4}  # Duplicates are removed
print(numbers)  # Output: {1, 2, 3, 4}
            
        

2. How to add elements to a Set?

Use the add() method to add an element to a set.

            
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)  # Output: {1, 2, 3, 4}
            
        

3. How to remove elements from a Set?

Use remove() or discard() to remove an element.

            
numbers = {1, 2, 3}

# Using remove() (raises error if element not found)
numbers.remove(2)
print(numbers)  # Output: {1, 3}

# Using discard() (no error if element not found)
numbers.discard(5)  # No error
            
        

4. How do you check if an element exists in a Set?

Use the in keyword to check for membership.

            
numbers = {1, 2, 3, 4}
print(3 in numbers)  # Output: True
print(5 in numbers)  # Output: False
            
        

5. What are Set Operations in Python?

Python supports mathematical set operations like union, intersection, difference.

            
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union
print(A | B)  # Output: {1, 2, 3, 4, 5, 6}

# Intersection
print(A & B)  # Output: {3, 4}

# Difference
print(A - B)  # Output: {1, 2}
            
        

6. What is the difference between remove() and discard()?

remove() raises an error if the element is not found, whereas discard() does not.

            
numbers = {1, 2, 3}

numbers.remove(2)  # Works fine
# numbers.remove(5)  # Raises KeyError

numbers.discard(5)  # No error
            
        

7. How to convert a List to a Set?

Use the set() function to remove duplicates.

            
numbers_list = [1, 2, 3, 3, 4, 4]
numbers_set = set(numbers_list)
print(numbers_set)  # Output: {1, 2, 3, 4}
            
        

8. How to get the number of elements in a Set?

Use the len() function.

            
numbers = {1, 2, 3, 4}
print(len(numbers))  # Output: 4
            
        

9. How to remove all elements from a Set?

Use the clear() method.

            
numbers = {1, 2, 3, 4}
numbers.clear()
print(numbers)  # Output: set()
            
        

10. What is Frozenset in Python?

A frozenset is an immutable version of a set.

            
numbers = frozenset([1, 2, 3, 4])
# numbers.add(5)  # Error: 'frozenset' object has no attribute 'add'
print(numbers)  # Output: frozenset({1, 2, 3, 4})