CBuilderLab· about 40 min· in the browser
Lab: lists, loops and dictionaries
Process lists with loops, list comprehensions and dictionaries.
Teaches: Python — lists, loops and dictionaries
Requires: Python — the basics
Theory
Almost all data handling is loops over lists. You will sum, filter and count occurrences — the same patterns that are later used on thousands of data points.
Sub-tasks
- medelvarde(tal) — mean — Return the mean of a list of numbers. Empty list → 0.0.
- udda(tal) — odd — Return a new list with only the odd numbers, in the same order.
- rakna(ord) — count — Return a dict word → number of occurrences.
- vanligast(ord) — most common — Return the most common word (on a tie: the one that came first).
The starter code
runs in your browserdef medelvarde(tal):
# TODO: summan delat med antalet; tom lista → 0.0
...
def udda(tal):
# TODO: list comprehension med villkor
...
def rakna(ord):
# TODO: dict med .get(o, 0) + 1
...
def vanligast(ord):
# TODO: använd rakna() och max(..., key=...)
...
You write the code; tests you cannot see decide whether it holds up. Create a free account to run the lab.
Try the diagnosticCreate a free accountExpected results
All tests green. medelvarde([1,2,3]) → 2.0; udda([1,2,3,4,5]) → [1,3,5]; rakna(['a','b','a']) → {'a':2,'b':1}; vanligast(['a','b','a']) → 'a'.
Common mistakes
- Division by zero for an empty list — handle that case first.
dict[key] += 1crashes when the key is missing: use.get(k, 0).vanligastwithmax(d, key=d.get)returns, on a tie, the one that came first in dict order — that is correct.