How to Create a Python Set of Size n?

5/5 - (1 vote)

Basic Solution

To create a set of n elements, pass a list or another iterable of n initial elements into the set() function. For example, set(range(n)) creates the set of n consecutive integers {1, 2, ..., n-1}. You can then add and remove the elements using the normal set methods such as add() or pop().

Here’s an example:

n = 100
my_set = set(range(n))
print(my_set)

'''
The output is:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}
'''

Set Comprehension

To create a set of size n by modifying an existing iterable of elements, you can use the set comprehension feature in Python. For example, {x*x for x in range(n)} creates the set of n square numbers in a single line of code.

Here’s the full code example:

n = 100
squared = {x*x for x in range(n)}
print(squared)

'''
The output is:
{0, 1, 1024, 4096, 4, 9216, 9, 16, 529, 3600, 4624, 25, 36, 2601, 49, 7225, 3136, 64, 576, 1089, 1600, 2116, 5184, 6724, 7744, 9801, 81, 8281, 6241, 100, 625, 121, 4225, 1156, 8836, 3721, 144, 1681, 2704, 5776, 4761, 2209, 676, 169, 3249, 9409, 196, 1225, 5329, 729, 225, 1764, 7396, 6889, 7921, 2809, 256, 2304, 6400, 3844, 4356, 784, 1296, 8464, 289, 3364, 4900, 5929, 1849, 9025, 324, 841, 1369, 2401, 2916, 5476, 361, 3969, 900, 9604, 4489, 400, 1936, 7056, 7569, 3481, 6561, 1444, 8100, 5041, 441, 961, 2500, 6084, 8649, 3025, 484, 2025, 1521, 5625}
'''

Feel free to watch my explainer video on set comprehension and have a look at the full guide on the Finxter blog too!

Python Set Comprehension – A Simple Formula Guide

πŸ‘‰ Recommended Tutorial: Python Set Comprehension Full Guide

Related – Creating a Python List of Size n

If you want to create a set of size n, another idea that works in some cases is to create a list of size n and then convert the list to a set. However, be aware of the fact that sets do not contain duplicates so a list of size n could easily become a set of size 1 if all elements in the list are duplicates!

Here’s how you can create a list of size n:

How to Create a Python List of Size n?

πŸ‘‰ Recommended Tutorial: How to Create a Python List of Size n?