Python Sets

In Python, a set is a collection data type that stores unordered, unique elements. It is useful when you need to eliminate duplicate values, perform mathematical set operations (like unions, intersections, etc.), or manage a collection of unique items efficiently.

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference

Creating a Set

Creating a set in Python can be done using curly braces {} or the set() function. Sets are useful for storing unique, unordered elements.

1. Using Curly Braces {}

You can create a set directly by placing items inside curly braces:


# Creating a set with curly braces
data_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(data_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

2. Using the set() Function

You can also create a set using the set() function, especially helpful when creating a set from other iterables like lists, tuples, or strings.


# Creating a set from a list
data_set = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(data_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

# Creating a set from a string (breaks it into unique characters)
char_set = set("python")
print(char_set)  # Output: {'p', 'y', 't', 'h', 'o', 'n'}

Note: To create an empty set, you must use set() because {} initializes an empty dictionary.

Python Sets – Questions and Answers

Q 1: What is a set in Python?

Ans: A set is an unordered collection of unique elements.

Q 2: Can sets contain duplicate elements?

Ans: No, sets automatically remove duplicates.

Q 3: Are sets mutable?

Ans: Yes, but elements themselves must be immutable.

Q 4: How do you create a set?

Ans: Using curly braces {1, 2, 3} or set() constructor.

Q 5: Can sets be indexed?

Ans: No, sets do not support indexing or slicing.

Python Sets – Objective Questions (MCQs)

Q1. Which of the following correctly creates a set in Python?






Q2. Which of the following statements about sets is true?






Q3. What will be the output of the following code?

s = {1, 2, 2, 3, 3, 3}
print(s)






Q4. Sets in Python cannot contain which of the following data types?






Q5. What will type({}) return in Python?






Related Python Sets Topics