OOP model
- Python course
- Intermediate
- Lesson 113/116
- 6 min
Set up the class hierarchy and ABCs.
Function layer: count unique
In this lesson you will write the say function. This function counts unique words with set:
def say(words):
return len(set(words))
print(say(words)) # 2The starting code includes the previous lesson's solution. You will add the say function and its call. set(words) removes duplicates; len gives the unique count.
This is the fundamental way to summarise data.
Practice Define and call the say function
Define def say(words): with return len(set(words)) in the body. Then write print(say(words)).
Starter code
# Word processing - word list
words = ["elma", "armut", "elma"]
print(len(words))
# define and call the say functionSample solution
words = ["elma", "armut", "elma"]
print(len(words))
def say(words):
return len(set(words))
print(say(words))Expected output
3 2
Next step: generator layer
The function layer is ready — you can count unique words. In the next lesson you will add a generator layer: producing words one by one with yield. This layer will save memory with large data.
Generators produce values without loading the whole list into memory; this makes them ideal for large files. Each lesson builds on top of the previous one and the starting code carries the previous solution.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the function layer
| Term | Meaning |
|---|---|
def say |
Function |
set(words) |
Removes duplicates |
len |
Gives count |
return |
Returns a value |
2 How many elements does set(["elma", "armut", "elma"]) have?
- 1
- 2 Correct answer
- 3
- 0
Explanation: set removes duplicates; elma stays once, total 2.
3 Complete the say function
def say(words):
return ____(set(words))
def say(words):
return len(set(words))
Explanation: len(set(words)) gives the unique word count.