Sitemap
LearnPython

From beginners to experts, find code snippets, practical examples, and step-by-step guides to master Python programming

Member-only story

All you know about Sets in Python-Part 1

--

Press enter or click to view image in full size

In Python, a Set is an unordered collection of unique data items. 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.

🔸A set is a collection of unique elements.

🔸The elements (items) in a set must be of an immutable type.

🔸Any immutable data type can be an element of a set (e.g. strings and integers). If you try to use a mutable data type inside a set, an exception (TypeError) is raised, as shown below.

set1 = {[1,2]}


Error :
TypeError: unhashable type: 'list'

🔸 Immutable types include:

  • Numbers (e.g., integers, floats)
  • Strings
  • Tuples (if all elements in the tuple are also immutable)

🔸 Mutable types (e.g., lists, dictionaries, sets) cannot be elements of a set.

Why can’t a set add mutable types?

  • Sets use a hash table internally to store elements. Immutable objects have a fixed hash value, which is required for efficient storage and retrieval in a…

--

--

Shaloo Mathew
Shaloo Mathew

Written by Shaloo Mathew

I love working with data and finding the stories it tells. Through analytics and technology, I aim to turn data into useful insights.

LearnPython
LearnPython

Published in LearnPython

From beginners to experts, find code snippets, practical examples, and step-by-step guides to master Python programming