Skip to content
AI-grafen
CBuilderLab· about 40 min· in the browser

Lab: lists, loops and dictionaries

Process lists with loops, list comprehensions and dictionaries.

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

  1. medelvarde(tal) — mean — Return the mean of a list of numbers. Empty list → 0.0.
  2. udda(tal) — odd — Return a new list with only the odd numbers, in the same order.
  3. rakna(ord) — count — Return a dict word → number of occurrences.
  4. vanligast(ord) — most common — Return the most common word (on a tie: the one that came first).

The starter code

runs in your browser
def 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 account

Expected 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] += 1 crashes when the key is missing: use .get(k, 0).
  • vanligast with max(d, key=d.get) returns, on a tie, the one that came first in dict order — that is correct.