MicroPython ‘tuple’ 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 custom types. MicroPython is no exception. Following are the standard or built-in data types of MicroPython (and Python):

  • Numeric
  • Boolean
  • Sequence Type
  • Set
  • Dictionary
Python data type hierarchy
FIG 1 - Source: geeksforgeeks.org

Tuples are part of the Python sequence family which also include lists and strings. Additionally, tuples 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, unchangeable1 and unindexed.
  • Dictionary is a collection which is ordered2 and changeable.

Tuple Definition

The tuple is similar to the list data type. However tuples are immutable. This means they are used to represent fixed collections of objects that can't be changed once created. Their main use is for code safety.

Tuple Creation

Tuples are created as a sequence of objects separated by commas. While not mandatory, it is good practice to enclose the sequence with ( ) brackets.

Table 1: tuple Declarations
Example Comment
1, 2, 3, 4, 5 Legal, but not best practice
(1, 2, 3, 4, 5) Recommended way to create a tuple
('man', 3.45,
  [11, 22, 33])
Tuple with multiple data types;
string, float and list
('woman') This is a string
('woman',) This is a tuple.
Note the trailing comma.

Accessing tuple Elements

Like a list, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index = 0.

Example 1

# Accessing a tuple element
#Indexing starts at zero (0)

t=('man', 3.45, [11, 22, 33])
print('The third element of the tuple is:', t[2])
            
Output:

The third element of the tuple is: [11, 22, 33]
            

Other iterable data types (string, list, dictionary) are convertible to tuples using the tuple() function (constructor).

Example 2

# Convert a string to a tuple

string1 = 'ABC'
tuple1 = tuple(string1)
print('The string is: ', string1)
print('The tuple is: ', tuple1)
            

Output:


The string is:  ABC
The tuple is:  ('A', 'B', 'C')
            

Tuples are immutable i.e. cannot be changed.

Example 3

# Attempting to make changes
# to a tuple gives an error

tuple1 = (1, 2, 3, 4, 5)
print('tuple1 =', tuple1)
print()

# Attempt to change an element
tuple1[2] = 5
print('tuple1 with new value =', tuple1)

            
Output:

tuple1 = (1, 2, 3, 4, 5)

Traceback (most recent call last):
  File "main.py", line 9, in <module>
TypeError: 'tuple' object doesn't support item assignment

            

More tuple Operators

Tuples share all operators, functions and methods of the list data type except those that attempt to change any tuple object members.

Table 2: tuple Operators
Operator Description
+

Concatenation; joins two or more tuples.

('A',) + ('B',) + ('C',)   → ('A', 'B', 'C')

*

Repeats a tuple a given number of times.

('AB', 'CD') * 2   → ('AB', 'CD', 'AB', 'CD')

==

Comparison operator tests whether two values are equal

t1 = ('A', 'B', 'C')
t2 = ('A', 'B', 'C')
t3 = ('A', 'C', 'B')

t1 == t2   → True
t1 == t3   → False

!=

Comparison operator tests whether two values are not equal

t1 = ('A', 'B', 'C')
t2 = ('A', 'C', 'B')

t1 != t2   → True

in

Membership operator

t = ('cat', 'dog')
'dog' in t   → True

not in

Membership operator

t = ('cat', 'dog')
'rabbit' not in t   → True

Tuple Functions

Table 3: MicroPython tuple Functions
Function Description
len()

Returns the number of elements in a tuple.

len(('ABC', 56, [1, 2, 3]))   → 3

max()

Returns the maximum value in a tuple of numbers.

max((100, -5, 76.23))   → 100

max((100, '-5', 76.23))
→ Error,'-5' is a string

min()

Returns the minimum value in a tuple of numbers.

min((100, -5, 76.23))   → -5

sorted(item
[, reverse = True|False])

Returns tuple as a sorted list.

t1 = ('d', 'a', 'g')
print(sorted(t1))   → ['a', 'd', 'g']

print(sorted(t1, reverse = True))
→ ['g', 'd', 'a']

Tuple Methods

Table 4: MicroPython tuple Methods
Method Description
index(item)

Returns index of first element with specified value.

t = ('A', 'B', 'C', 'B')
print(t.index('B'))   → 1

print(t.index('Z'))
  → Error: 'object not in sequence'

count(item)

Returns number of elements with specified value.

t = ('A', 'B', 'C', 'B')
print(t.count('B'))   → 2
print(t.count('Z'))   → 0