Basics of set and creating a set in Python

By Abhinash & Priya Chetty on August 28, 2022

Previous articles have discussed the Python syntax and in-built functions for handling the string and list data type, both of which are sequence-type data. This article focuses on another sequence type data, the set and Frozenset and creating a set and frozenset. Sets are similar to lists but unlike lists, sets contain unique values in an unordered sequence.

NOTE

Like list sets are also mutable but the elements are immutable like boolean, string, integers and tuples.

Since sets are mutable, they cannot be elements of another set. In the case of Frozensets, they are immutable sets such that they cannot be changed once created.

x = {1, 2, 3, 4}
y = {'a', 'b', 'c'}

Creating a set using set()

Apart from declaring a set, they can also be created by converting various data types into a set, using the set() function.

String to set

When a string is converted to a set, each character becomes an element of the set. Multiple occurrences of an alphabet are omitted from the set.

f = set('Happy')
print(f)
{'H', 'p', 'a', 'y'}

List to set

Python list can also be changed to a set using the set function. In this case, too the multiple occurrences of the same value will be omitted.

f = ['H','A','P','P','Y']
s = set(f)
print(s)
{'H', 'P', 'Y', 'A'}

Similarly, a set can also be created from a list with integers and boolean values.

Tuple to set

Tuples are another type of sequence data in Python, in which the elements are immutable. These can also be converted to sets using the set()function.

seasons = ('winter','spring','summer','autumn')
set = set(seasons)
print(set)
{'summer', 'autumn', 'spring', 'winter'}

Frozen sets

Another form of set, the Frozenset are essentially a mutable form of sets. Therefore, once Frozensets are created, they cannot be changed. Frozensets in Python are created using the frozenset() function.

seasons = ('winter','spring','summer','autumn')
set = frozenset(seasons)
print(set)
#OUTPUT
frozenset({'summer', 'autumn', 'spring', 'winter'})

Frozensets can also be created from other types of sequence data.

f = ['H','A','P','P','Y']
s = frozenset(f)
print(s)
frozenset({'H', 'P', 'Y', 'A'})
NOTES

Discuss