← Back to list

Data Science Day 11 Sets

Sets in Python

Tharun B S · 2026-04-20 08:50 · 0 claps · 2.9 min read
#data-science #python #python-set
Open on Medium ↗
Wiki topics: ML · Machine Learning 🔬 · Science · General

Data Science Day 11 Sets

Sets in Python

Above image is AI generated

What are Python Sets?

Python sets are a data type for unordered collections that hold distinct elements. Although the elements themselves must be immutable (such as strings, tuples, or numbers), they are mutable, which means that elements can be added or removed after creation.

For what tasks are they helpful?

For tasks involving membership testing, removing duplicates from sequences, and carrying out mathematical set operations, sets are especially helpful.

Why Sets Are Unindexed?

In a list, items are stored in a specific sequence (0, 1, 2…). In a set, Python calculates a “hash value” for each element, which determines its position in memory.

  • No Fixed Order: Because the position depends on the hash value, the elements don’t stay in a “first-in, first-out” or sorted order.
  • Performance: This design allows Python to check if an item exists in the set almost instantly, regardless of how large the set is. This is known as O(1) time complexity.
  • Unique Elements: Since the position is tied to the value, the set can immediately see if a value already occupies its “spot,” preventing duplicates.

How to Perform a Search Operation?

Since we cannot use an index (like my_set[0]), we search for elements using the in keyword. This is the most efficient way to check for membership.

1. Membership Testing

The in operator returns a boolean value (True or False).

fruits = {"apple", "banana", "cherry"}

# Check if "apple" exists
if "apple" in fruits:
    print("Found apple!")

2. Finding Specific Data

If we need to find an item that meets a certain condition, we can use a for loop or a set comprehension.

numbers = {10, 25, 30, 45, 50}

# Find all numbers greater than 30
results = {x for x in numbers if x > 30}
print(results)  # Output: {45, 50}

Important features of Python sets include:

· Unordered: When a set is printed or iterated, the elements’ order may change because it lacks a defined order. There is no support for indexing.

· Unique elements: Only one instance of each element is stored, and sets automatically handle duplicate values.

· Mutable: You can use remove(), discard(), pop(), or clear() to get rid of elements and add() or update() to add new ones.

· Immutable elements: A set’s individual elements must be immutable (hashable), even though the set itself is mutable. This implies that mutable items, such as lists or other sets, cannot be kept directly inside of a set.

· Hashing: Because sets are internally implemented using hash tables, searching, adding, and removing elements are made incredibly efficient.

Curly braces {} are used when creating sets.

my_set = {1, 2, 3, 4, 5}
empty_set = set() # Creates an empty set ({} creates an empty dictionary)
set_from_list = set([1, 2, 2, 3]) # {1, 2, 3}

Typical Set Operations:

Adding elements:

Ÿ update() (multiple elements from an iterable) and

Ÿ add() (single element).

The following functions are used to remove elements:

Ÿ pop() removes and returns an arbitrary element,

Ÿ clear() removes all elements,

Ÿ discard() throws an error if no element is found, and remove() raises a KeyError if it is.

Use the in keyword when testing for membership (e.g., element in my_set).

Set operations in mathematics:

Set1 | set2 or set1.union(set2) are examples of union: | operators or union() methods.

Intersection: intersection() method or intersection: & operator (e.g., set1.intersection(set2) or set1 & set2).

Set1 — set2 or set1.difference(set2) are examples of the difference: — operator or difference() method.

Set1 ^ set2 or set1.symmetric_difference(set2) are examples of symmetric_difference() methods or the ^ operator.

Press enter or click to view image in full size

Internal operations of Set

· This is predicated on a hash table, a type of data structure. A linked list is created when multiple values are present at the same index position and are appended to that index position.

· The key being the members set with higher optimizations to the time complexity, Python sets are implemented using a dictionary with dummy variables.


메타데이터
post_id
5475c4aaa618
slug
data-science-day-11-sets-5475c4aaa618
url
https://medium.com/@tharunbs352/data-science-day-11-sets-5475c4aaa618
canonical_url
https://medium.com/@tharunbs352/data-science-day-11-sets-5475c4aaa618
author_url
https://medium.com/@tharunbs352
status
ok
fetched_at
2026-06-24 16:30:55