Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6813975
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T20:37:58+00:00 2026-05-26T20:37:58+00:00

To make the question clear, I’ll use a specific example. I have a list

  • 0

To make the question clear, I’ll use a specific example.

I have a list of college courses, and each course has a few fields (all of which are strings). The user gives me a string of search terms, and I return a list of courses that match all of the search terms. This can be done in a single list comprehension or a few nested for loops.

Here’s the implementation. First, the Course class:

class Course:
    def __init__(self, date, title, instructor, ID, description, instructorDescription, *args):
        self.date = date
        self.title = title
        self.instructor = instructor
        self.ID = ID
        self.description = description
        self.instructorDescription = instructorDescription
        self.misc = args

Every field is a string, except misc, which is a list of strings.

Here’s the search as a single list comprehension. courses is the list of courses, and query is the string of search terms, for example “history project”.

def searchCourses(courses, query):
    terms = query.lower().strip().split()
    return tuple(course for course in courses if all(
            term in course.date.lower() or
            term in course.title.lower() or
            term in course.instructor.lower() or
            term in course.ID.lower() or
            term in course.description.lower() or
            term in course.instructorDescription.lower() or
            any(term in item.lower() for item in course.misc)
        for term in terms))

You’ll notice that a complex list comprehension is difficult to read.

I implemented the same logic as nested for loops, and created this alternative:

def searchCourses2(courses, query):
    terms = query.lower().strip().split()
    results = []
    for course in courses:
        for term in terms:
            if (term in course.date.lower() or
                term in course.title.lower() or
                term in course.instructor.lower() or
                term in course.ID.lower() or
                term in course.description.lower() or
                term in course.instructorDescription.lower()):
                break
            for item in course.misc:
                if term in item.lower():
                    break
            else:
                continue
            break
        else:
            continue
        results.append(course)
    return tuple(results)

That logic can be hard to follow too. I have verified that both methods return the correct results.

Both methods are nearly equivalent in speed, except in some cases. I ran some tests with timeit, and found that the former is three times faster when the user searches for multiple uncommon terms, while the latter is three times faster when the user searches for multiple common terms. Still, this is not a big enough difference to make me worry.

So my question is this: which is better? Are list comprehensions always the way to go, or should complicated statements be handled with nested for loops? Or is there a better solution altogether?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T20:37:59+00:00Added an answer on May 26, 2026 at 8:37 pm

    IMHO, they’re good programming practice when they’re clearer (or at least, no less clear) and more succinct than the alternative. In this case neither option is that clear. Personally, I’d stick the search logic in the Course class. This makes more sense to me as the logic is linked to the class.

    class Course:
        def __init__(self, date, title, instructor, ID, description, instructorDescription, *args):
            self.date = date
            self.title = title
            self.instructor = instructor
            self.ID = ID
            self.description = description
            self.instructorDescription = instructorDescription
            self.misc = args
    
        def matches_term(self, term):
            if term in self.date.lower():
                return True
            # etc
            return False
    

    And then you can use a simpler generator (or list) expression for the search:

    def searchCourses(courses, query):
        terms = query.lower().strip().split()
        return tuple(course for course in courses
                     if all(course.matches_term(term)
                            for term in terms)
                    )
    

    A simple test:

    courses = (
        Course("today", "", "", "", "", ""),
        Course("wednesday", "", "", "", "", ""),
        Course("today", "", "", "", "", ""),
        Course("sunday", "", "", "", "", ""),
    )
    
    results = searchCourses(courses, "on today or wednesday")
    for course in results:
        print course.date
    

    which outputs:

    today
    wednesday
    today
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My question may not make sense but I have valid reason. We use .net
Edit2: I just want to make sure my question is clear: Why, on each
I have simplified my design to make this question more clear. (Design of models
I am attaching an image to make my question clear. I have defined the
Ok, I'm going to try to make this more clear because my last question
Brief question What command can I use to make my DataSet refresh it's connection
The question is in the title but to make it clearer when you use
I hope I can make this question clear enough. I'm looking to put a
I think the following code will make the question clear. // My class var
Hi let me make my question clear. Two people using my app are connected

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.