Microbit Python Computer Science
Beginner
80 mins
Teacher/Student led
What you need:
Chromebook/Laptop/PC

Lists and Tuples

Explore the essentials of Python data structures in this lesson. You'll learn about creating and manipulating lists, performing operations like sorting and iteration, and understand the differences between mutable lists and immutable tuples through hands-on coding tasks.
Learning Goals Learning Outcomes Teacher Notes

Live Class Feed

This is a live feed of the latest activity by your students on this lesson. It will update in real-time as they work on the lesson.
Load previous activity

    1 - Introduction

    In this lesson we will:

    1. Understand lists as mutable, ordered collections and learn to create, access, and modify them.
    2. Perform basic operations on lists, including appending, removing, popping, slicing, sorting, and reversing.
    3. Master iteration over lists using for loops to process data, such as calculating sums or displaying items.
    4. Explore tuples as immutable alternatives to lists, including creation, access, and iteration.
    5. Compare lists vs tuples to decide when to use each based on mutability, efficiency, and use cases like dictionary keys.
    6. Apply these concepts in exercises, such as sorting lists, filtering even numbers, and calculating sums through coding tasks.

    2 - What are Lists?

    Lists are ordered collections of items that can be changed (mutable). They are defined using square brackets [] and can hold different data types, like numbers, strings, or even other lists. Lists are useful for storing multiple related items, such as a list of scores or names, and they allow you to organise data efficiently in your programs.

    For example, fruits = ["apple", "banana", "cherry"] creates a list. You can access items by index, starting from 0, e.g., fruits[0] is "apple". Negative indices count from the end, so fruits[-1] is "cherry". Lists are dynamic, so you can add or remove items, and they can even be empty, like empty_list = [].

    In the editor, add this complete code:

    from microbit import *
    
    fruits = ["apple", "banana", "cherry"]
    
    display.scroll(fruits[0])
    
    display.scroll(str(len(fruits)))

    Breakdown:

    • fruits = ["apple", "banana", "cherry"]: Creates the list.
    • display.scroll(fruits[0]): Shows "apple".
    • display.scroll(str(len(fruits))): Shows the length (3).
    Run the code. You should see "apple" followed by "3" scroll on the display.
    Experiment: Change the list items, access different indices including negative ones, or create an empty list and check its length.

    3 - Basic List Operations

    Lists are mutable, meaning you can change them after creation. Common operations include adding items with append(), removing specific values with remove(), or removing by index with pop() (which also returns the removed item). You can also slice lists to get sublists, similar to strings, e.g., list[1:3] extracts elements from index 1 to 2.

    These operations help you manage and manipulate data dynamically in your programs.

    Update your code to this complete version:

    from microbit import *
    
    numbers = [1, 2, 3]
    numbers.append(4)
    display.scroll(str(numbers))
    numbers.remove(2)
    display.scroll(str(numbers))
    removed = numbers.pop(0)  # Removes and returns the first item
    display.scroll("Removed: " + str(removed))
    sliced = numbers[0:2]
    display.scroll(str(sliced))

    Breakdown:

    • numbers.append(4): Adds 4, list becomes [1, 2, 3, 4].
    • numbers.remove(2): Removes 2, list becomes [1, 3, 4].
    • numbers.pop(0): Removes and returns 1, list becomes [3, 4].
    • sliced = numbers[0:2]: Gets [3, 4].
    Run the code. You should see "[1, 2, 3, 4]", "[1, 3, 4]", "Removed: 1", "[3, 4]" scroll.
    Experiment: Try popping a different index.

    4 - Iterating over Lists

    Iteration means going through each item in a list one by one, which is a powerful way to process data in collections. In Python, we often use a for loop for this purpose. A for loop allows you to execute a block of code repeatedly for each element in the list. This is especially useful for tasks like displaying all items, performing calculations on each one, or building summaries, such as calculating the sum or average of numbers in a list.

    For example, if you have a list of scores, you can loop through them to show each score on the micro:bit display or add them up to find the total. Remember, the code inside the loop must be indented correctly (usually with four spaces) to indicate it belongs to the loop.

    Update your code to this complete version:

    from microbit import *
    
    scores = [85, 92, 78, 90]
    for score in scores:
        display.scroll(str(score) + " ")
    total = 0
    for score in scores:
        total += score
    display.scroll("Total: " + str(total))

    Breakdown:

    • scores = [85, 92, 78, 90]: Creates a list of exam scores.
    • First for score in scores: This loop goes through each item in the list, assigning it to the variable 'score' one at a time, and scrolls it on the display with a space.
    • total = 0: Initialises a variable to keep track of the sum.
    • Second for score in scores: Loops through the list again, adding each score to the total (which will be 85 + 92 + 78 + 90 = 345).
    • display.scroll("Total: " + str(total)): Displays the final total.

    Note: We use two separate loops here for clarityโ€”one for displaying and one for summingโ€”but you could combine them into one loop if you wanted to do both at the same time.

    Run the code. You should see each score scroll one by one (85, 92, 78, 90), followed by "Total: 345".
    Experiment: Add more scores to the list and rerun. Or, modify the second loop to calculate the average by dividing the total by the length of the list (len(scores)). Try combining the loops: inside one loop, both scroll the score and add to the total.

    5 - Sorting Lists

    Sorting arranges list items in order. Use sort() for ascending order (modifies the list) or sorted() for a new sorted list. You can sort in descending order by passing reverse=True to these functions. Additionally, you can reverse the order of a list without sorting using the reverse() method, which modifies the list in place. These methods work both on numbers and strings.

    Update your code to this complete version:

    from microbit import *
    
    numbers = [5, 3, 8, 1]
    numbers.sort()
    display.scroll(str(numbers))
    numbers.reverse()
    display.scroll(str(numbers))
    fruits = ["cherry", "apple", "banana"]
    sorted_fruits = sorted(fruits, reverse=True)
    display.scroll(str(sorted_fruits))

    Breakdown:

    • numbers.sort(): Sorts to [1, 3, 5, 8].
    • numbers.reverse(): Reverses the sorted list to [8, 5, 3, 1].
    • sorted(fruits, reverse=True): Returns ["cherry", "banana", "apple"] (sorted descending) without changing the original.
    Run the code. See "[1, 3, 5, 8]", "[8, 5, 3, 1]", and "['cherry', 'banana', 'apple']" scroll.
    Experiment: Try using sort(reverse=True) or reverse() on the numbers list instead of sort(). Observe the difference.

    Unlock the Full Learning Experience

    Get ready to embark on an incredible learning journey! Get access to this lesson and hundreds more in our Digital Skills Curriculum.

    Copyright Notice
    This lesson is copyright of DigitalSkills.org. Unauthorised use, copying or distribution is not allowed.
    ๐Ÿช Our website uses cookies to make your browsing experience better. By using our website you agree to our use of cookies. Learn more