Fundamentals 9 min read

Python Set Tutorial – Creation, Operations, and Usage

This article introduces Python's set data type, explains how to create empty and non‑empty sets, demonstrates common operations such as add, update, remove, discard, pop, clear, iteration, set algebra operators, and describes the immutable frozenset, all illustrated with code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Set Tutorial – Creation, Operations, and Usage

Python includes a built‑in data type called set , which represents an unordered collection of unique elements and supports membership testing, duplicate elimination, and mathematical operations such as union, intersection, difference, and symmetric difference.

Creating Sets

Sets can be created using curly braces or the set() function. The argument to set() must be an iterable (e.g., list, tuple, dictionary). Because sets discard duplicates, they are useful for deduplicating strings, lists, or tuples.

1. Creating an empty set

<code>&gt;&gt; s = set()
&gt;&gt; s
set()
&gt;&gt; s1 = set([])  # list
&gt;&gt; s1
set()
&gt;&gt; s2 = set(())  # tuple
&gt;&gt; s2
set()
&gt;&gt; s3 = set({})  # dictionary
&gt;&gt; s3
set()</code>

Note: Use set() for an empty set; {} creates an empty dictionary.

2. Creating a non‑empty set

<code>&gt;&gt; s1 = set([1, 2, 3, 4])
&gt;&gt; s1
{1, 2, 3, 4}
&gt;&gt; s3 = set({'a': 2, 'b': 3, 'c': 4})
&gt;&gt; s3
{'c', 'a', 'b'}</code>

When converting a dictionary to a set, only the keys are taken.

Set Operations

1. Adding Elements

add() inserts a single element as a whole:

<code>&gt;&gt; s = set('one')
&gt;&gt; s
{'e', 'o', 'n'}
&gt;&gt; s.add('two')
&gt;&gt; s
{'e', 'two', 'o', 'n'}</code>

update() iterates over the supplied iterable and adds each element individually, removing duplicates:

<code>&gt;&gt; s = set('one')
&gt;&gt; s.update('two')
&gt;&gt; s
{'e', 'n', 't', 'w', 'o'}</code>

2. Removing Elements

setVar.remove(element) deletes element and raises a KeyError if it is absent.

<code>&gt;&gt; s = set('one')
&gt;&gt; s.remove('e')
&gt;&gt; s
{'n', 'o'}</code>

setVar.discard(element) also deletes element but does nothing if the element is not present.

<code>&gt;&gt; sList = set([1, 2, 3, 4, 5])
&gt;&gt; sList.discard(1)
&gt;&gt; sList
{2, 3, 4, 5}</code>

s.pop() removes and returns an arbitrary element, raising KeyError when the set is empty.

<code>&gt;&gt; sList = {2, 3, 4, 5}
&gt;&gt; sList.pop()
2</code>

s.clear() empties the set.

<code>&gt;&gt; sList.clear()
&gt;&gt; sList
set()</code>

3. Iterating Over a Set

Iteration works like any other iterable:

<code>&gt;&gt;&gt; s = set('one')
&gt;&gt;&gt; for i in s:
...     print(i)
 e
 o
 n
&gt;&gt;&gt; for index, i in enumerate(s):
...     print(index, i)
0 e
1 o
2 n</code>

4. Set Algebra Operators

Intersection ( &amp; ), union ( | ), and difference ( - ) use familiar symbols:

<code># Intersection
&gt;&gt; st1 = set('python')
&gt;&gt; st2 = set('htc')
&gt;&gt; st1 &amp; st2
{'h', 't'}
# Union
&gt;&gt; st3 = set('two')
&gt;&gt; st1 | st3
{'p', 't', 'w', 'y', 'h', 'o', 'n'}
# Difference
&gt;&gt; st1 - set('4589')
{'1', '3', '2', '7', '6'}</code>

The difference() method provides the same result as the subtraction operator.

Set Comparison

Sets can be compared using &gt; , &gt;= , &lt; , &lt;= , == , and != to test subset/superset relationships and equality.

<code>&gt;&gt;&gt; s1 = set([1, 2, 3, 4, 5])
&gt;&gt;&gt; s2 = set([1, 2, 3, 4])
&gt;&gt;&gt; s1 &gt; s2
True
&gt;&gt;&gt; s1 == s2
False
&gt;&gt;&gt; s1 != s2
True</code>

Immutable Sets – frozenset

The frozenset type is an immutable version of set ; its contents cannot be changed after creation.

<code>&gt;&gt; f = frozenset()
&gt;&gt; f
frozenset([])
&gt;&gt; f = frozenset('asdf')
&gt;&gt; f
frozenset({'a', 's', 'd', 'f'})
&gt;&gt; f = frozenset([1, 2, 3, 4])
&gt;&gt; f
frozenset({1, 2, 3, 4})</code>

These immutable sets can be used as dictionary keys or elements of other sets.

PythonCollectionsdata structuresset operationssetfrozenset
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.