Sitemap
The Pythoneers

Your home for innovative tech stories about Python and its limitless possibilities. Discover, learn, and get inspired.

Member-only story

Understand Sets In Python With Examples

7 min readJul 5, 2021

--

Press enter or click to view image in full size
Photo by Jefferson Santos on Unsplash

A set is similar to lists and tuples. It is a collection of elements stored inside a variable. A set can contain more than one object and each element can be of different types. The elements in a set are separated using commas and enclosed in curly braces.

Note: A set can never contain duplicate elements.

There are different ways on how to use a list let us look at a few:

Creating sets

  1. Simple Set

Program:

set1 = {5, 6, 7}
print(set1)
s = {5, 6, 7, 6, 7}
print(s)
se = {5, 6, 7, [6, 7]}
print(se)
Output:
{5, 6, 7}
{5, 6, 7}
Traceback (most recent call last):
File “<string>”, line 5, in <module>
se = {5, 6, 7, [6, 7]}
TypeError: unhashable type: ‘list’

Explanation: From the above print statements, we can observe that

  • A set never shows duplicates as output.
  • A set can never contain a list embedded inside.

2. Set with mixed data types

Program:

set2 = {5, ‘python’, ‘23’}

--

--

Amit Chauhan
Amit Chauhan

Written by Amit Chauhan

Data Scientist, AI/ML/DL, Azure Cloud

The Pythoneers
The Pythoneers

Published in The Pythoneers

Your home for innovative tech stories about Python and its limitless possibilities. Discover, learn, and get inspired.