Listing tasks
- Python course
- Beginner
- Lesson 85/116
- 6 min
Print tasks with list_tasks.
Listing tasks (list_tasks)
Let us write a list_tasks function to list the added tasks. With enumerate we get both the index and the value:
def list_tasks():
for i, t in enumerate(tasks):
print(i, t)This shows tasks numbered: 0 Buy bread, 1 Buy milk. The index will be used later for completing tasks.
How enumerate works
enumerate(tasks) yields a (index, value) pair at each loop:
for i, t in enumerate(["Bread", "Milk"]):
print(i, t)
# 0 Bread
# 1 MilkThis is more Pythonic than a classic range(len(tasks)) loop. It is ideal for accessing index and value at once.
This is a very common pattern in Python.
Practice Add the list_tasks function
Define a function called list_tasks with no parameters. In the body build a loop for i, t in enumerate(tasks): and do print(i, t). Call it with list_tasks().
Starter code
# Todo CLI - bos gorev listesi
tasks = []
print(tasks)
def add_task(title):
tasks.append(title)
add_task("Ekmek al")
add_task("Sut al")
# list_tasks fonksiyonunu ekleSample solution
def list_tasks():
for i, t in enumerate(tasks):
print(i, t)
list_tasks()Expected output
[] 0 Buy bread 1 Buy milk
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the list_tasks body
def list_tasks():
for i, t in ____(tasks):
print(i, t)
def list_tasks():
for i, t in enumerate(tasks):
print(i, t)
Explanation: enumerate gives both index and value.
2 What does list(enumerate(["a", "b"])) return?
- ["a", "b"]
- [0, 1]
- [(0, "a"), (1, "b")] Correct answer
- [("a", 0), ("b", 1)]
Explanation: enumerate yields (index, value) pairs.
3 Match the listing parts
| Term | Meaning |
|---|---|
enumerate |
Index and value |
for i, t in |
Loop shape |
print(i, t) |
|
list_tasks() |
Call |