Creation and Modification of Sets

To perform relevant operations and calculations on sets, we first need to create a set. Once a set is created, we can add or remove elements from it. Note: conceptually, set elements are unordered and cannot be indexed; the value of a set element cannot be changed unless we remove it and add a new value.

Creating Sets

【Excel VBA】

Excel VBA does not have a built-in set data type, but it has a Collection object — a collection object familiar to VB or VBA programmers, which can conveniently store and manage different objects. However, this book does not use the Collection object to discuss sets; instead, we use arrays to represent sets. For creating arrays in Excel VBA, please refer to Chapter 7.

【Python】

We can create a set directly using curly braces {}. Elements in a set can be of different data types. Below is an example of creating a set:

code.python
>>> st = {1, 'a'}
>>> st
{1, 'a'}

Note: elements in a set can be unordered but must be unique (i.e., no duplicates).

We can also create a set using the set() function, or convert other iterable objects into sets. Iterable objects include strings, ranges, lists, tuples, dictionaries, etc.

code.python
>>> set({1, 'a'})          # Directly create
{1, 'a'}
>>> set('abcd')            # Convert string
{'b', 'c', 'd', 'a'}
>>> set(range(5))          # Convert range
{0, 1, 2, 3, 4}
>>> set([1, 'a'])          # Convert list
{1, 'a'}
>>> set((1, 'a'))          # Convert tuple
{1, 'a'}
>>> set({1: 'a', 2: 'b'})  # Convert dictionary
{1, 2}

If there are duplicate elements in the iterable object, only one will be retained in the resulting set. Using this feature of sets, we can remove duplicates from given data.

code.python
>>> st = set([1, 'a', 1, 'a'])
>>> st
{1, 'a'}

The number of elements in a set is called the length of the set. We can use the len() function to calculate the length of a set.

code.python
>>> st = {1, 2}
>>> len(st)
2

We can also directly calculate the length of a set as follows:

code.python
>>> len({1, 2})
2

Adding and Removing Set Elements

【Excel VBA】

This book uses arrays to represent sets. For adding and removing array elements, please refer to Chapter 7.

【Python】

We can use the add() method of a set object to add elements to a set. Below, we create a set st and add the element 4 to it.

code.python
>>> st = {1, 'a'}
>>> st.add(4)
>>> st
{1, 4, 'a'}

We can use the remove() method of a set object to remove an element from a specified set. Below, we remove the element 4 from set st.

code.python
>>> st.remove(4)
>>> st
{1, 'a'}

We can use the clear() method of a set object to empty all elements in the set.

code.python
>>> st.clear()
>>> st
set()