MicroPython ‘set’ Data Type
Contents
Introduction
MicroPython is a “slim” version of Python specifically designed with a small footprint to efficiently run on memory constrained microcontrollers.
Computer languages have a built-in set of data types along with user capability to define additional custom types. MicroPython is no exception. Following are the standard or built-in MicroPython data types:
- Numeric
- Boolean
- Sequence Type
- Set
- Dictionary
Sets can also be considered a collection type
There are four collection data types in the Python programming language:
- List is a collection which is ordered and changeable.
- Tuple is a collection which is ordered and unchangeable.
- Set is a collection which is unordered, unchangeable and unindexed.
- Dictionary is a collection which is ordered[1] and changeable.
Set Definition
A set is a mutable (can be changed) unordered collection of unique and immutable (can't be changed) objects. An important point here is that while the members of the set are immutable, the set can have members deleted and added.
Sets are defined with elements enclosed in curly brackets { } and separated by commas. A set can also be created with the set function (constructor) set(). It is important to note that the set constructor takes one and only one parameter; see example below.
Set members may be of mixed types.
Example | Comment |
---|---|
{1, 2, 3, 4, 5} | legal |
{'Apple', [1, 2, 3]} | illegal, the list object is mutable |
{'Apple', tuple([1, 2, 3])} | legal, the tuple object is immutable |
{'Apple', (1, 2, 3)} | legal, both string and tuple are immutable |
set([1, 2, 3, 4, 5]) | legal, a list is converted to a set type |
set(1, [2, 3, 4, 5]) | illegal, two parameters are passed to set() |
Set order is arbitrary, thus there is no sort() method, unlike the list data type which can be sorted.
An item only appears once in a set regardless of the number of times it is added.
Example 1
# Examples of the set data type
set_of_numbers = {1, 2, 2, 2, 3, 3, 4, 5}
print("set_of_numbers =", set_of_numbers)
set_of_apples = set('apples')
print("set_of_apples =", set_of_apples)
Output:
set_of_numbers = {1, 2, 3, 4, 5} set_of_apples = {'p', 'a', 'l', 'e', 's'}
This example shows that regardless of the number of times the same element is added to a set, it will only appear once as a member of that set. Sets cannot be sorted so when output (e.g. with print()) the order of the elements cannot be predicted.
Set Operators
The MicroPython set type supports operations corresponding to mathematical set theory; including difference, union and intersection.
Most set operations in Python can be performed in two different ways:
- By operator
- By method
The following table shows operator versus method equivalents where defined.
Operation | Operator | Method |
---|---|---|
Difference | - | difference() |
Union | | | union() |
Intersection | & | intersection() |
Symmetric Difference | ^ | symmetric_difference() |
Subset | < | issubset() |
Superset | > | issuperset() |
These operators and methods are explained below in Table 2 and Table 3 respectively.
Set operations by Operator
If an operator (see Table 2) is used then the operands must all be of type set. Any operand not of type set must be explicitly converted to a set with the set() function (constructor) else an error will occur.
Example 2 - Set Operations by Operatorset declaration. s1 = {1, 2, 3, 4, 5} intersection operator examples. Returns set of elements common to both sets. s1 & {4, 5, 6, 7} ⇒ {4, 5} s1 & (4, 5, 6, 7) ⇒ error, second operand is a tuple s1 & set((4, 5, 6, 7)) ⇒ {4, 5}
Operator | Description |
---|---|
== | Comparison operator tests whether two values are equal s1 = {1, 2, 3, 4, 5}
s1 == s2 ⇒ False
|
!= | Comparison operator tests whether two values are not equal s1 = {1, 2, 3, 4, 5}
s1 != s2 ⇒ True |
in | Membership operator s1 = {1, 2, 3, 4, 5}
3 in s1 ⇒ True |
not in | Membership operator s1 = {1, 2, 3, 4, 5}
3 not in s2 ⇒ True |
- | Difference operator returns a set of elements from the first set that aren't elements of the second set. s1 = {1, 2, 3, 4, 5}
s1 - s2 ⇒ {1, 2, 3}
|
| | Union operator returns a set with all elements from both sets. s1 = {1, 2, 3, 4, 5}
s1 | s2
|
& | Intersection operator returns a set of elements common to both sets. s1 = {1, 2, 3, 4, 5}
s1 & s2 ⇒ {4, 5} |
^ | Symmetric difference operator returns a set that contains all items from both sets, except items that are present in both sets. s1 = {1, 2, 3, 4, 5}
s1 ^ s2 ⇒ {8, 1, 2, 3, 6, 7} |
< | Subset operator returns True if all elements of the second set are found in the first set. a = {1, 2, 3, 4, 5}
b < a ⇒ True
|
> | Superset operator returns True if all elements in the second set exists in the first set. a = {1, 2, 3, 4, 5}
a > b ⇒ True
|
Set Operations by Method
The parameter(s) of the method approach aren't restricted and may be of any immutable data type. MicroPython implicitly converts any immutable non-set types to type set before performing the operation.
Example 3 - Set Operations by Methodset declaration. s1 = {1, 2, 3, 4, 5} intersection method examples. Returns set of elements common to both sets. s1.intersection({4, 5, 6, 7}) ⇒ {4, 5} Legal even though the parameter is a tuple. s1.intersection((4, 5, 6, 7)) ⇒ {4, 5}
In the second example, MicroPython implicitly converts the tuple to a set before applying the intersection operation.
The following table shows the set method operations.
Method | Description |
---|---|
difference() | Returns a set of elements from the first set that aren't elements of the second set. s1 = {1, 2, 3, 4, 5}
s1.difference(s2)
|
union() | Returns a set with all elements from both sets. s1 = {1, 2, 3, 4, 5}
s1.union(s2)
|
intersection() | Returns a set of elements common to both sets. s1 = {1, 2, 3, 4, 5}
s1.intersection(s2)
|
symmetric
_difference() |
Returns a set that contains all items from both sets, except items that are present in both sets. s1 = {1, 2, 3, 4, 5}
s1.symmetric_difference(s2) ⇒ {8, 1, 2, 3, 6, 7}
|
issubset() | Returns True if all elements of the second set are found in the first set. a = {1, 2, 3, 4, 5}
b.issubset(a) ⇒ True
|
issuperset() | Returns True if all elements in the second set exists in the first set. a = {1, 2, 3, 4, 5}
b.issuperset(a) ⇒ False
|
isdisjoint() | Returns True if both sets have no common elements.
a = {1, 2, 3, 4, 5}
a.isdisjoint(b) ⇒ False
|
Set Functions
Function | Description |
---|---|
len() | Returns the number of elements in a set. len({'it', 'is', 2.5})
|
max() | Returns the maximum value in a set of numbers. max({100, -5, 76.23})
|
min() | Returns the minimum value in a set of numbers. min({100, -5, 76.23})
|
sorted(item
[, reverse = True|False]) |
Returns the set as a sorted list. s1 = {'d', 'a', 'u'} print(sorted(s1))
print(sorted(s1, reverse = True))
|
Set Methods
Method | Description |
---|---|
add(item) | Adds one (and only one) element to the set. s1 = {1, 2, 3}
|
update(item 1[, item 2, ...item n]) | Adds one or more iterables to the set. A = {1, 2, 3}
A.update(B, C)
|
remove(item) | Removes item from set. Exception raised if item not in set. A = {1, 2, 3} A.remove(2) {3, 1} A.remove(4)
|
discard(item) | Removes item from set. Exception not raised if item not in set. A = {1, 2, 3} A.discard(2)
A.discard(4) ⇒ {3, 1, 2} |
pop() | Removes a random element from a set. A = {1, 2, 3}
|
clear() | Removes all elements from set. A = {'A', 'B', 'C', 'B'}
|
MicroPython also supports the following methods:
- intersection_update()
- difference_update()
- symmetric_difference_update()
These operate similarly to the methods intersection(), difference() and symmetric_difference() but modify an existing set based on the contents of a second set rather than returning a new set.
Copy the following code into the Mu Editor, save and flash to the micro:bit. Click on the REPL button to see the program's output.
Example 4
# Demonstrates the use of
# the method 'intersection_update()'.
# Removes the items that are not present
# in both sets and returns the result
# in set 'X'.
X = {'A', 'B', 'C'}
Y = {'C', 'D', 'E', 'F'}
print('\nBefore:')
print('X is', X)
print('Y is', Y)
X.intersection_update(Y)
print('\nAfter:')
print('X is', X)
print('Y is', Y)
Output:
Before: X is {'C', 'A', 'B'} Y is {'E', 'D', 'C', 'F'} After: X is {'C'} Y is {'E', 'D', 'C', 'F'}