# CircuitPython 101: Basic Builtin Data Structures

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/058/727/medium800/circuitpython_blinka.png?1533733642)

This guide is part of a series on some of the more advanced features of Python, and specifically CircuitPython. Are you new to using CircuitPython? No worries, [there is a full getting started guide here](https://learn.adafruit.com/welcome-to-circuitpython).

Adafruit suggests using the Mu editor to edit your code and have an interactive REPL in CircuitPython. [You can learn about Mu and its installation in this tutorial](https://learn.adafruit.com/welcome-to-circuitpython/installing-mu-editor).

With the introduction of [the new SAMD51 (M4) based boards](https://www.adafruit.com/?q=m4), CircuitPython gets far more interesting. Not only do they have a clock speed almost three times faster than the SAMD21 (M0 boards) and they have six times as much RAM. Not only do CircuitPython programs run significantly faster, they can be much larger and/or work with much more data. With this space comes the capability to move beyond simple scripts to more elaborate programs.

The goal of this series of guides is to explore Python's mechanisms and techniques that will help make your more ambitious CircuitPython programs more manageable, understandable, and maintainable.

In this guide, we'll look at several basic ways to organize data in Python: **Tuples** , **Lists** , and **Dictionaries**.

We'll use examples that deal with playing tunes using the Adafruit&nbsp;`pulseio` library.&nbsp;Below is the circuit used featuring an [Adafruit ItsyBitsy M4 Express](https://www.adafruit.com/product/3800 "Adafruit ItsyBitsy M4 Express"). With a few minimal tweaks to the wiring and code, this will work with any of the M4 Express boards. Note that only the final example makes use of the buttons and an OLED display.

![](https://cdn-learn.adafruit.com/assets/assets/000/057/566/medium800/circuitpython_song_book_player_bb.png?1531413715)

Parts

Any of these M4 boards will do nicely.

### Part: ItsyBitsy M4 Express
quantity: 1
ATSAMD51 based ItsyBitsy with extra flash.
[ItsyBitsy M4 Express](https://www.adafruit.com/product/3800)

### Part: Feather M4 Express
quantity: 1
ATSAMD51 based Feather with extra flash.
[Feather M4 Express](https://www.adafruit.com/product/3857)

### Part: Metro M4 Express
quantity: 1
ATSAMD51 based Metro with extra flash.
[Metro M4 Express](https://www.adafruit.com/product/3382)

To play the notes, you'll need a buzzer.&nbsp;For the interface you'll need an OLED display and a couple buttons.

### Part: Piezo buzzer
quantity: 1
Piezo buzzer that you can drive with any frequency square wave.
[Piezo buzzer](https://www.adafruit.com/product/160)

### Part: Breadboardable tactile button
quantity: 1
Little clicky switches are standard input "buttons" on electronic projects.
[Breadboardable tactile button](https://www.adafruit.com/product/367)

### Part: 128x32 I2C OLED display
quantity: 1
Small, but very readable OLED display with an I2C interface.
[128x32 I2C OLED display](https://www.adafruit.com/product/931)

## Tools and Materials

- A small solderless breakboard
- wires for use of the breadboard
- microUSB data cable fro connecting the M4 board to your computer

<sub><em>Key image by <span class="mw-mmv-author"><a title="User:Jorge Stolfi" href="https://commons.wikimedia.org/wiki/User:Jorge_Stolfi">Jorge Stolfi</a></span> an is CC BY-SA 3.0</em></sub>

# CircuitPython 101: Basic Builtin Data Structures

## Tuple

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

```auto
&gt;&gt;&gt; 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:

```auto
&gt;&gt;&gt; t[0]
1
&gt;&gt;&gt; t[1]
2
&gt;&gt;&gt; t[2]
'three'
```

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

```auto
(261, 0.25)
```

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

```auto
def play_note(note):
    pwm = pulseio.PWMOut(board.D12, duty_cycle = 0, frequency=note[0])
    pwm.duty_cycle = 0x7FFF
    time.sleep(note[1])
    pwm.deinit()
```

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

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/CircuitPython_101/basic_data_structures/play_note/code.py

# CircuitPython 101: Basic Builtin Data Structures

## List

A list in Python is just that: a list of things. We use lists all the time: shopping lists, TO-DO lists. Even Santa uses lists.

Lists in Python have features that jive with our general idea of lists:

- They can be empty.
- They can have any number of things in them.
- They can have different kinds of things in them.
- You can append (add to the end) new things to them.
- You can insert new things anywhere in them (this is easier with lists that aren't written on paper)
- You can sort them to put them in some particular order (if everything in them can be compared).
- You can see how long they are.
- You can remove things from them.
- You can replace things in them.
- You can check if something is in them.
- You can combine them.
- You can throw them out when you're done with them.

Making a list looks a lot like making a tuple, except that square brackets are used:

```auto
&gt;&gt;&gt; my_list = [1, 2, "three"]
```

In Python, lists and tuples are both a kind of sequence, which means that they have many capabilities in common. For example, you can find their length:

```auto
&gt;&gt;&gt; len(my_list)
3
```

Accessing items is the same:

```auto
&gt;&gt;&gt; my_list[0]
1
&gt;&gt;&gt; my_list[1]
2
```

If you use negative indices, they are from the end rather than the start. That makes sense, but -1 is the last item, -2 is the second to last, etc. There really isn't a way around this since -0 isn't really a thing. You can use negative indices with tuples as well as with lists, but it isn't generally as useful. Tuples tend to be small, and for a specific purpose they tend to be the same size with the same type of information in each position. In our tuple example, the frequency was always at position 0, and the duration at position 1.

Lists are more dynamic, both in size and content, unlike tuples.

Info: 

Changing the thing at a specific location of a list is much like accessing whatever is there: you simply give it a new value.

```auto
&gt;&gt;&gt; my_list[2] = 42
&gt;&gt;&gt; my_list
[1, 2, 42]
```

Appending new items to a list is easy:

```auto
&gt;&gt;&gt; my_list.append(3)
&gt;&gt;&gt; my_list
[1, 2, 42, 3]
```

As is inserting something anywhere in the list:

```auto
&gt;&gt;&gt; my_list.insert(1, 99)
&gt;&gt;&gt; my_list
[1, 99, 2, 42, 3]
```

The first argument to `insert` is where in the list to put the new item, at index 1 in the above example (i.e. the second position). Everything else will get moved to one position larger to make room.

Lists have many more capabilities that we won't consider here. See [the python documentation](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)&nbsp;for more information.

## Making songs

We used tuples to form notes that can be played by combining a frequency and a duration, and we wrote a function to pull that information out of a tuple and play the tone on the CircuitPlayground Express' built-in speaker. The next step is to put those individual notes together into songs. Before we can do that we need to make a slight adjustment to the `play_note` function to add rests. We can make the decision to use a frequency of 0 Hertz indicate a rest, or silence:

```auto
def play_note(note):
    if note[0] != 0:
        pwm = pulseio.PWMOut(board.D12, duty_cycle = 0, frequency=note[0])
        pwm.duty_cycle = 0x7FFF
    time.sleep(note[1])
    if note[0] != 0:
        pwm.deinit()
```

With that we can now construct a list of note tuples.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/CircuitPython_101/basic_data_structures/song_list/code.py

# CircuitPython 101: Basic Builtin Data Structures

## Dictionary

Dictionaries allow us to associate a value with a name (generally called a key). It's more general than that, but that's probably the most common use.&nbsp;

A common way to construct a dictionary to use the brace notation:

```auto
&gt;&gt;&gt; d = {'one': 1, 'two': 2, 'three': 3}
&gt;&gt;&gt; d
{'one': 1, 'three': 3, 'two': 2}
```

Notice that dictionaries are not ordered. That's fine, because they don't use numeric indices, they use keys.

As with lists, we can find out how many key-value pairs are in a dictionary using:

```auto
&gt;&gt;&gt; len(d)
3
```

Accessing data in a dictionary is done similarly to lists:

```auto
&gt;&gt;&gt; d['three']
3
```

as is changing it:

```auto
&gt;&gt;&gt; d['three'] = 'not3'
&gt;&gt;&gt; d
{'one': 1, 'three': 'not3', 'two': 2}
```

Adding a key/value pair to a dictionary is the same as modifying one:

```auto
&gt;&gt;&gt; d['four'] = 4
&gt;&gt;&gt; d
{'four': 4, 'one': 1, 'two': 2, 'three': 'not3'}

```

To remove from a dictionary we use the `del` function:

```auto
&gt;&gt;&gt; del(d['three'])
&gt;&gt;&gt; d
{'four': 4, 'one': 1, 'two': 2}
```

Finally, we can check if a dictionary contains a specific key:

```auto
&gt;&gt;&gt; 'one' in d
True
&gt;&gt;&gt; 'three' not in d
True
&gt;&gt;&gt; 'three' in d
False
```

## Formats - Songbook

So we have notes represented by tuples that we can put together in a list to make a song. What if we want multiple songs? We could have each in a separate variable. Let's add the additional requirement that we want to connect an I2C OLED display to show a list of songs that we can select from. Having songs in separate variables means that everything has to be hardcoded. That's seldom a good idea. What we'd like is to have things stored in such a way that we just have to add a song and have the menu automatically be updated to reflect it. We can do this by storing them in a dictionary, keyed by name (edited for brevity):

```auto
songbook = {'Twinkle Twinkle': [(C4, 0.5), (C4, 0.5), (G4, 0.5), (G4, 0.5), (A4, 0.5), ...],
                         
            'ItsyBitsy Spider': [(G4, 0.5), (C4, 0.5), (C4, 0.5), (C4, 0.5), (D4, 0.5), ...],

            'Old MacDonald': [(G4, 0.5), (G4, 0.5), (G4, 0.5), (D4, 0.5), (E4, 0.5), ...]
           }

```

With that done, we can get the names of the songs by `songbook.keys()`. This isn't a list, although it can be used for some list-like things. It can't be indexed, however. We need to convert it to a list in order to be able to do that: `list(songbook.keys())`. While we're at it, we should go ahead and sort it so that it will display in alphabetical order: `sorted(list(songbook.keys()))`.

![](https://cdn-learn.adafruit.com/assets/assets/000/057/561/medium800/circuitpython_song_list_player.jpg?1531411036)

Here is the complete code:

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/CircuitPython_101/basic_data_structures/song_book/code.py

# CircuitPython 101: Basic Builtin Data Structures

## Closing

Tuples, Lists, and Dictionaries provide three different ways to organize information. Choosing the best way to do this can make the difference between a program that is awkward to change and one that is a pleasure to work with.

Next time we'll have a look at functions and some guidelines for writing good ones.


## Featured Products

### Adafruit ItsyBitsy M4 Express featuring ATSAMD51

[Adafruit ItsyBitsy M4 Express featuring ATSAMD51](https://www.adafruit.com/product/3800)
What's smaller than a Feather but larger than a Trinket? It's an **Adafruit ItsyBitsy M4 Express** featuring the **Microchip ATSAMD51**! Small, powerful, with a ultra fast ATSAMD51 Cortex M4 processor running at 120 MHz - this microcontroller board is perfect...

Out of Stock
[Buy Now](https://www.adafruit.com/product/3800)
[Related Guides to the Product](https://learn.adafruit.com/products/3800/guides)
### Adafruit Feather M4 Express - Featuring ATSAMD51

[Adafruit Feather M4 Express - Featuring ATSAMD51](https://www.adafruit.com/product/3857)
It's what you've been waiting for, the Feather M4 Express featuring ATSAMD51. This Feather is fast like a swift, smart like an owl, strong like a ox-bird (it's half ox, half bird, OK?) This feather is powered by our new favorite chip, the **ATSAMD51J19** -&nbsp; with...

In Stock
[Buy Now](https://www.adafruit.com/product/3857)
[Related Guides to the Product](https://learn.adafruit.com/products/3857/guides)
### Adafruit Metro M4 feat. Microchip ATSAMD51

[Adafruit Metro M4 feat. Microchip ATSAMD51](https://www.adafruit.com/product/3382)
Are you ready? Really ready? Cause here comes the fastest, most powerful Metro ever. The **Adafruit Metro M4** featuring the **Microchip ATSAMD51**. This Metro is like a bullet train, with its 120MHz Cortex M4 with floating point support. Your code will zig and zag...

In Stock
[Buy Now](https://www.adafruit.com/product/3382)
[Related Guides to the Product](https://learn.adafruit.com/products/3382/guides)
### Piezo Buzzer

[Piezo Buzzer](https://www.adafruit.com/product/160)
Piezo buzzers are used for making beeps, tones and alerts. This one is petite but loud! Drive it with 3-30V peak-to-peak square wave. To use, connect one pin to ground (either one) and the other pin to a square wave out from a timer or microcontroller. For the loudest tones, stay around 4 KHz,...

In Stock
[Buy Now](https://www.adafruit.com/product/160)
[Related Guides to the Product](https://learn.adafruit.com/products/160/guides)
### Tactile Button switch (6mm) x 20 pack

[Tactile Button switch (6mm) x 20 pack](https://www.adafruit.com/product/367)
Little clicky switches are standard input "buttons" on electronic projects. These work best in a PCB but [can be used on a solderless breadboard as shown in this tutorial](https://learn.adafruit.com/adafruit-arduino-lesson-6-digital-inputs?view=all). The pins are normally...

In Stock
[Buy Now](https://www.adafruit.com/product/367)
[Related Guides to the Product](https://learn.adafruit.com/products/367/guides)
### Monochrome 128x32 I2C OLED graphic display

[Monochrome 128x32 I2C OLED graphic display](https://www.adafruit.com/product/931)
These displays are small, only about 1" diagonal, but very readable due to the high contrast of an OLED display. This display is made of 128x32 individual white OLED pixels, each one is turned on or off by the controller chip. Because the display makes its own light, no backlight is...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/931)
[Related Guides to the Product](https://learn.adafruit.com/products/931/guides)
### Adafruit METRO M0 Express - designed for CircuitPython

[Adafruit METRO M0 Express - designed for CircuitPython](https://www.adafruit.com/product/3505)
Metro is our series of microcontroller boards for use with the Arduino IDE. This new **Metro M0 Express** board looks a whole lot like our&nbsp;[original Metro 328](https://www.adafruit.com/product/2488), but with a huge upgrade. Instead of the ATmega328, this Metro...

In Stock
[Buy Now](https://www.adafruit.com/product/3505)
[Related Guides to the Product](https://learn.adafruit.com/products/3505/guides)
### Circuit Playground Express

[Circuit Playground Express](https://www.adafruit.com/product/3333)
 **Circuit Playground Express** is the next step towards a perfect introduction to electronics and programming. We've taken the original Circuit Playground Classic and made it even better! Not only did we pack even more sensors in, we also made it even easier to...

In Stock
[Buy Now](https://www.adafruit.com/product/3333)
[Related Guides to the Product](https://learn.adafruit.com/products/3333/guides)

## Related Guides

- [Adafruit Feather M0 Express](https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython.md)
- [Adafruit Metro M0 Express](https://learn.adafruit.com/adafruit-metro-m0-express.md)
- [Adafruit Trinket M0](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino.md)
- [Adafruit Circuit Playground Express](https://learn.adafruit.com/adafruit-circuit-playground-express.md)
- [Adafruit Metro M4 Express featuring ATSAMD51](https://learn.adafruit.com/adafruit-metro-m4-express-featuring-atsamd51.md)
- [Adafruit Feather M4 Express](https://learn.adafruit.com/adafruit-feather-m4-express-atsamd51.md)
- [Cosplay Floating LED Fireball with Motion Sensing](https://learn.adafruit.com/cosplay-fireball-prop-with-motion-sensing.md)
- [Circuit Playground Digital Input](https://learn.adafruit.com/circuit-playground-digital-input.md)
- [Dance-Reactive Tutu Sparkle Skirt](https://learn.adafruit.com/dance-reactive-tutu-sparkle-skirt.md)
- [Make It Sense](https://learn.adafruit.com/make-it-sense.md)
- [Controlling a Classic Nintendo R.O.B. Robot Using Circuit Playground Express](https://learn.adafruit.com/controlling-a-classic-nintendo-r-o-b-robot-using-circuit-playground-express.md)
- [How to Program SAMD Bootloaders](https://learn.adafruit.com/how-to-program-samd-bootloaders.md)
- [Make It Glow: How to Solder NeoPixels, A Beginner's Guide](https://learn.adafruit.com/make-it-glow-how-to-solder-neopixels-a-beginners-guide.md)
- [Using Servos With CircuitPython and Arduino](https://learn.adafruit.com/using-servos-with-circuitpython.md)
- [CircuitPython OLED Watch Clock](https://learn.adafruit.com/circuitpython-oled-watch.md)
- [Light Up Paper Dragon Wall Sconce](https://learn.adafruit.com/light-up-paper-dragon-wall-sconce.md)
- [Four Seasons Fairy Bottle Lanterns](https://learn.adafruit.com/four-seasons-fairy-bottle-lanterns.md)
- [3D Printed Daft Punk Helmet](https://learn.adafruit.com/3d-printed-daft-punk-helmet.md)
- [Make your own PCB with Eagle, OSH Park, and Adafruit!](https://learn.adafruit.com/making-pcbs-with-oshpark-and-eagle.md)
- [NeoPixie Dust Bag](https://learn.adafruit.com/neopixel-pixie-dust-bag.md)
- [UFO Flying Saucer with Circuit Playground Express](https://learn.adafruit.com/ufo-circuit-playground-express.md)
