Robotics & Artificial Intelligence
What is meant by Python Sets? Explain with the help of an example.
Python Funda
2 Likes
Answer
In Python, a set is a built-in data type that represents an unordered collection of unique elements. Sets are used to store multiple items in a single variable, with elements enclosed within curly braces { } and separated by commas. A set is unordered, unchangeable (in terms of modifying individual elements) and unindexed.
Characteristics of a Set:
- Unordered: The elements do not have a specific order, so they may appear in different orders.
- Unique Elements: A set automatically removes duplicate elements.
- Mutable: Elements can be added or removed from a set after its creation.
Example:
My_set = {"red", "blue", "green", "yellow"}
print(My_set)
Output: {'red', 'green', 'yellow', 'blue'}
If we try adding duplicates, the set will retain only unique values. For example, My_set = {"red", "blue", "green", "yellow", "blue", "green"} will store only {'red', 'blue', 'green', 'yellow'}.
Answered By
1 Like