Python Sets
Python Sets

Python Sets

In Python, a Set is an unordered collection of data items that are unique. Learn to create a set and add, update, and remove items from a set. Also, learn the different set methods and operations such as union, intersection, differance, and many more.

In Python, a Set is an unordered collection of data items that are unique. In other words, Python Set is a collection of elements (Or objects) that contains no duplicate elements.

Unlike List, Python Set doesn’t maintain the order of elements, i.e., It is an unordered data set. So you cannot access elements by their index or perform insert operation using an index number.

In this tutorial, we will learn Set data structure in general, different ways of creating them, and adding, updating, and removing the Set items. We will also learn the different set operations.

image

Characteristics of a Set

A set is a built-in data structure in Python with three key characteristics:

  1. Unordered: Items in a set have no fixed order, unlike lists. When you access a set, the items may appear in different orders. Sets don't assign index values to their items.
  2. Unchangeable: Set items must be immutable. While you can add or remove items from a set, you cannot modify the items themselves. Though the set can be modified as a whole, each element within it must be of an immutable type.
  3. Unique: A set cannot contain duplicate items—each value must be unique.

Table of contents

1.0 Creating a Set

2.0 Accessing items of a set

3.0 Find the length of a set

4.0 Adding items to a Set

5.0 Removing item(s) from a set

6.0 Set Operations

7.0 Copying a Set

8.0 Subset and Superset

9.0 Find whether two sets are disjoint

10. Sort the set

11. Using Python built-in functions for Set

12. Set: all() and any()

13. Set: max() and min()

14. Frozen Set

15. Nested Sets

16. Set comprehension

When to use a Set Data structure?