BCA / B.Tech 6 min read

Sets in Python

Set in Python:


In Python, a set is an unordered, mutable, and unique collection of items. A set is used when you need to store different types of items without any specific order. The main advantage of a set is that it cannot contain duplicate items, allowing you to create a collection of only unique values.

Features of a Set:
Unordered collection, unique items, mutable (items can be added or removed), and can contain heterogeneous data.

Creating a Set:
A set can be created within curly braces `{}` or by using the `set()` function.

Accessing Items in a Set:
Items in a set cannot be accessed directly through an index because sets are unordered. However, you can check if an item exists in a set using the `in` operator.

Built-in Methods:
Common methods include `add()`, `update()`, `clear()`, `copy()`, `discard()` (does not raise an error if the item is not found), and `remove()` (raises a KeyError if the item is not found).