What is a set in Python?

What is a set in Python?

a) A collection of unique unordered elements
b) A collection of ordered elements
c) A collection of key-value pairs
d) A list with fixed elements

Answer:

a) A collection of unique unordered elements

Explanation:

A set in Python is a collection of unique, unordered elements. This means that a set does not allow duplicate values, and the elements have no specific order. Sets are commonly used to perform mathematical set operations like union, intersection, and difference.

# Example of a set
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)  # Output: {'banana', 'cherry', 'apple'}

In this example, the set fruits contains three unique elements. Even though “apple” is listed twice, it only appears once in the set.

Sets are useful when you need to ensure that all elements in a collection are unique or when you need to perform set-based operations.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top