Python Lists and Functions for Beginners
Store values in lists, index and loop over them, then write your own functions with parameters and return.
Variables hold one value. But many programs work with collections: a list of scores, a shopping list, a set of quiz questions. And as programs grow, you’ll want to reuse code instead of copying it. This lesson covers both tools: lists and functions.
Lists: many values in one variable
A list is an ordered collection of values in square brackets, separated by commas:
fruits = ["apple", "banana", "cherry"]
scores = [72, 88, 95]
empty = []
Getting items by index
Each item has a position called an index. Indexes start at 0, not 1:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[-1]) # cherry (negative counts from the end)
Asking for an index that doesn’t exist, like fruits[3], gives an IndexError.
Changing lists
Lists can change after you create them:
fruits.append("mango") # add to the end
fruits[0] = "kiwi" # replace an item
fruits.remove("banana") # remove by value
print(fruits) # ['kiwi', 'cherry', 'mango']
print(len(fruits)) # 3
len() tells you how many items a list has. It also works on strings: len("hello") is 5.
Looping over a list
The for loop from Lesson 3 works directly on lists:
scores = [72, 88, 95]
total = 0
for s in scores:
total = total + s
print(f"Average: {total / len(scores):.1f}") # Average: 85.0
Python also has built-in helpers: sum(scores) gives 255, max(scores) gives 95 and min(scores) gives 72. You can check whether something is in a list with in: "kiwi" in fruits is True.
Functions: reusable blocks of code
You’ve already used built-in functions like print(), len() and input(). Now you’ll write your own with def:
def greet(name):
print(f"Hello, {name}!")
greet("Aisha")
greet("Ben")
Hello, Aisha!
Hello, Ben!
defstarts the definition, followed by the function name and brackets.nameis a parameter: a placeholder for the value you pass in.- The indented block is the function’s body. It only runs when you call the function.
Returning a value
print() shows something on screen, but often you want a function to give back a result you can use. That’s what return does:
def average(numbers):
return sum(numbers) / len(numbers)
result = average([72, 88, 95])
print(result) # 85.0
print(result >= 70) # True
When Python reaches return, the function stops and hands the value back to the caller. A function without return gives back the special value None.
Why functions matter
- Reuse: write the logic once, call it many times.
- Readability:
average(scores)is clearer than three lines of maths. - Fewer bugs: fix a mistake in one place instead of everywhere you copied it.
A good rule: if you’ve copied the same few lines twice, turn them into a function.
Practice: a grade checker
def letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "Needs work"
scores = [95, 82, 67]
for s in scores:
print(s, letter_grade(s))
95 A
82 B
67 Needs work
This combines everything so far: a list, a loop, a function with a parameter, if/elif/else and return.
Key takeaways
- Lists hold ordered collections in square brackets; indexes start at 0, and
-1is the last item. append(),remove()andlen()change and measure lists;forloops go through them.defcreates a function; parameters receive values when you call it.returnhands a result back; without it, a function returnsNone.
Sources checked: the official Python Tutorial sections on lists and defining functions.
In Lesson 5 you’ll use all of this to build a small quiz game.
Progress is saved in this browser only.