Python
Search and filter
Write search and filtering with list comprehension.
Search with a list comprehension
To find posts by a specific author you use a list comprehension: [p for p in self.posts if p.author == author]. This single line returns the matching posts as a new list.
The search_by_author method simply returns this line. From outside you call blog.search_by_author("Ayşe"); since the result is a list, len(...) tells you how many posts matched.
Exercise Add a search_by_author method
Add a method def search_by_author(self, author): to the Blog class above. Its body should be return [p for p in self.posts if p.author == author]. Then create a blog, add three posts (two by "Ayşe"), call results = blog.search_by_author("Ayşe") and print the count with print(len(results)).
Show example solution
from dataclasses import dataclass, field
@dataclass
class Post:
title: str = ""
content: str = ""
author: str = ""
comments: list = field(default_factory=list)
def add_comment(self, comment):
self.comments.append(comment)
@dataclass
class Comment:
author: str = ""
text: str = ""
@dataclass
class Blog:
posts: list = field(default_factory=list)
def add_post(self, post):
self.posts.append(post)
def search_by_author(self, author):
return [p for p in self.posts if p.author == author]
blog = Blog()
blog.add_post(Post(title="One", author="Ayşe"))
blog.add_post(Post(title="Two", author="Ali"))
blog.add_post(Post(title="Three", author="Ayşe"))
results = blog.search_by_author("Ayşe")
print(len(results))
The filter pattern
The comprehension form [item for item in seq if cond] is a filter pattern: if the condition is true, the item goes into the new list; otherwise it's skipped. This is shorter than writing a loop and an if.
You can reuse the same pattern elsewhere: filter by length (if len(p.title) > 5), by date range, or by content (if "python" in p.content). Change the condition; the structure stays.
Test yourself
-
What does [p for p in posts if p.author == a] produce?
- A single value
- A dictionary
- A tuple
- A list of matching items
Show answer
A list of matching items — A list comprehension produces a new list of the items that match the condition.
-
Match the list comprehension parts
- for
- Loop keyword
- if
- Condition keyword
- return
- Yielding the result
- in
- Membership test
-
Complete the filter condition
return [p for p in self.posts if p.author == ____]
Show answer
return [p for p in self.posts if p.author == author]
Next lesson: Putting it together