CodeBlanks Logo Icon CodeBlanks

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.

Practice 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)).

Starter code

main.py
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)

# Add a search_by_author method to Blog

# Create a blog, add three posts (two by Ayşe), search and print

Sample solution

main.py
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))

Expected output

2

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.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does [p for p in posts if p.author == a] produce?

  • A single value
  • A dictionary
  • A tuple
  • A list of matching items Correct answer

Explanation: A list comprehension produces a new list of the items that match the condition.

2 Match the list comprehension parts

Term Meaning
for Loop keyword
if Condition keyword
return Yielding the result
in Membership test

3 Complete the filter condition

Question
return [p for p in self.posts if p.author == ____]
Answer
return [p for p in self.posts if p.author == author]

Explanation: The method compares against its author parameter.

All lessons in Intermediate