Using Loops to Iterate Over Data Structures in MicroPython on Raspberry Pi Pico

Posted

in

by

MicroPython on Raspberry Pi Pico provides several data structures for storing and manipulating data. These include lists, tuples, sets, and dictionaries. Loops are a powerful tool for iterating over these data structures and performing operations on their elements.

Let’s take a look at some examples of how loops can be used to iterate over data structures in MicroPython.

  1. Iterating over a List

A list is a collection of items, and we can iterate over it using a for loop. Here’s an example:

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Iterate over the list and print each number
for number in numbers:
    print(number)

In this example, we create a list of numbers and then iterate over it using a for loop. For each number in the list, we print it to the console.

  1. Iterating over a Tuple

A tuple is similar to a list, but it is immutable, which means it cannot be modified once it is created. Here’s an example of how to iterate over a tuple using a for loop:

# Create a tuple of fruits
fruits = ('apple', 'banana', 'cherry')

# Iterate over the tuple and print each fruit
for fruit in fruits:
    print(fruit)

In this example, we create a tuple of fruits and then iterate over it using a for loop. For each fruit in the tuple, we print it to the console.

  1. Iterating over a Set

A set is an unordered collection of unique items. We can iterate over a set using a for loop just like we do with lists and tuples. Here’s an example:

# Create a set of colors
colors = {'red', 'green', 'blue'}

# Iterate over the set and print each color
for color in colors:
    print(color)

In this example, we create a set of colors and then iterate over it using a for loop. For each color in the set, we print it to the console.

  1. Iterating over a Dictionary

A dictionary is a collection of key-value pairs. We can iterate over a dictionary using a for loop, but we need to use the items() method to access both the keys and values. Here’s an example:

# Create a dictionary of students and their grades
grades = {'Alice': 85, 'Bob': 90, 'Charlie': 95}

# Iterate over the dictionary and print each student and their grade
for student, grade in grades.items():
    print(f'{student}: {grade}')

In this example, we create a dictionary of students and their grades and then iterate over it using a for loop. For each student and their corresponding grade, we print them to the console.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *