Basics

Python Sets

Python Sets for Unique Elements

Python sets store unique elements, with union and intersection operations.

Introduction to Python Sets

Python sets are a collection type that is unordered, mutable, and does not allow duplicate elements. Sets are useful when you want to store unique items, and they provide operations like union, intersection, difference, and symmetric difference.

Creating a Set

You can create a set by placing all the items (elements) inside curly braces {}, separated by commas, or by using the built-in set() function.

Accessing Set Elements

Sets do not support indexing, so you cannot access elements by index like lists or tuples. However, you can loop through the set using a for loop.

Adding and Removing Elements

To add an element to a set, use the add() method. To remove an element, you can use the remove() or discard() method. Note that using remove() on a non-existent item will raise a KeyError, while discard() will do nothing.

Set Operations

Sets support several mathematical operations, such as union, intersection, difference, and symmetric difference. These operations can be performed using methods or operators.

Conclusion

Python sets are a powerful tool for storing unique elements and performing efficient mathematical operations. Their ability to handle duplicates automatically and perform set operations makes them a valuable data structure in many programming scenarios.