Tuples are a lightweight way to group information together. They are created using a comma separated sequence of items in parentheses:

>>> t = (1, 2, 'three')

Notice that there is no need for the parts of a tuple to be the same type of thing. E.g. in the example above we have a tuple with two integers and a string.

Once you have a tuple, you can access the parts of it using an indexing notation:

>>> t[0]
>>> t[1]
>>> t[2]

Notice that tuples (and lists) in Python are 0 based. That is, the index of the first item is 0, the index of the second item is 1, and so on. You can think of this as being how far from the first item you want to access.

Tuples are immutable. That means that once one is created, it can't be changed: you can't add or delete items, or change the values in the tuple.

Let's use tuples to represent notes in a song. Each note has a frequency and a duration. Frequency is in hertz and duration is in seconds. A C4 for quarter of a second would be

(261, 0.25)

We can use this to write a play_note function using pulseio:

def play_note(note):
    pwm = pulseio.PWMOut(board.D12, duty_cycle = 0, frequency=note[0])
    pwm.duty_cycle = 0x7FFF

From this, we can write some simple code to play notes.

# SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import board
import pwmio

C4     = 261
C_SH_4 = 277
D4     = 293
D_SH_4 = 311
E4     = 329
F4     = 349
F_SH_4 = 369
G4     = 392
G_SH_4 = 415
A4     = 440
A_SH_4 = 466
B4     = 493

def play_note(note):
    if note[0] != 0:
        pwm = pwmio.PWMOut(board.D12, duty_cycle = 0, frequency=note[0])
        # Hex 7FFF (binary 0111111111111111) is half of the largest value for a 16-bit int,
        # i.e. 50%
        pwm.duty_cycle = 0x7FFF
    if note[0] != 0:

a4_quarter = (A4, 0.25)
c4_half = (C4, 0.5)


This guide was first published on Jul 13, 2018. It was last updated on Jun 11, 2024.

This page (Tuple) was last updated on Jun 11, 2024.

Text editor powered by tinymce.