In this lesson we will:
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).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].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.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.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.
len(scores)
). Try combining the loops: inside one loop, both scroll the score and add to the total.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.sort(reverse=True)
or reverse()
on the numbers list instead of sort()
. Observe the difference.