Lesson 3 of 5 18 min read
Lists, dictionaries and functions
Store collections of data in lists and dictionaries, and organise your code into reusable functions.
In this lesson you will
- Create, index, slice and modify lists
- Store and look up structured data with dictionaries
- Define functions with parameters, default values and return values
Lists
A list is an ordered, changeable collection:
skills = ["Python", "SQL", "Git"]
print(skills[0]) # Python (indexes start at 0)
print(skills[-1]) # Git (negative indexes count from the end)
skills.append("Docker")
skills.remove("SQL")
print(skills) # ['Python', 'Git', 'Docker']
print(len(skills)) # 3
print(skills[0:2]) # ['Python', 'Git'] (slice: start included, end excluded)Loop over a list directly, or use enumerate when you also need the position:
for position, skill in enumerate(skills, start=1):
print(position, skill)List comprehensions build a new list in one readable line:
marks = [45, 82, 67, 91]
passed = [m for m in marks if m >= 50] # [82, 67, 91]
doubled = [m * 2 for m in marks] # [90, 164, 134, 182]Dictionaries
A dictionary stores key–value pairs, perfect for describing one thing with named fields:
student = {
"name": "Arjun",
"year": 2,
"skills": ["Python", "Git"],
}
print(student["name"]) # Arjun
student["year"] = 3 # update a value
student["city"] = "Kochi" # add a new key
print(student.get("email", "none")) # none (default when the key is missing)
for key, value in student.items():
print(key, "→", value)student (contains "name": "Arjun", "year": 3, "skills": ["Python", "Git"], "city": "Kochi")
Using student["email"] for a missing key raises a KeyError; .get() lets you provide a fallback instead.
A list of dictionaries is a common way to represent table-like data:
courses = [
{"title": "Python Basics", "hours": 10},
{"title": "SQL Essentials", "hours": 8},
]
total_hours = sum(c["hours"] for c in courses) # 18Functions
Define a function with def. Use return to send a result back:
def average(numbers):
if not numbers: # an empty list is "falsy"
return 0
return sum(numbers) / len(numbers)
def greet(name, greeting="Hello"): # greeting has a default value
return f"{greeting}, {name}!"
print(average([70, 80, 90])) # 80.0
print(greet("Asha")) # Hello, Asha!
print(greet("Asha", "Welcome")) # Welcome, Asha!A function without a return statement returns the special value None.
Walkthrough: a word-frequency counter
def word_counts(text):
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
result = word_counts("Learn build rise learn build learn")
print(result) # {'learn': 3, 'build': 2, 'rise': 1}Step by step: lower() makes the text lowercase, split() breaks it into words, and for each word the dictionary count goes up by one, starting from 0 when the word is new. Counting things with a dictionary is a pattern you'll use constantly in data work.
Hands-on exercise
Create a list of five dictionaries, each describing a student with a name and a marks value. Write a function top_student(students) that returns the name of the student with the highest marks, and a function class_average(students) that returns the average. Print both results. Bonus: use a list comprehension to build a list of the names of students who scored 75 or more.
Knowledge check
3 questions • 70% to pass • Practice only, no certificate
Key concepts
- Lists are ordered and changeable; index from 0, use negative indexes from the end, and slice with [start:end].
- Dictionaries map keys to values; use .get() to supply a default for missing keys.
- Functions are defined with def, can have default parameter values and return None if they don't return anything else.
- Lists of dictionaries are a simple way to represent table-like data.
