I a list of strings A and a list of keywords B. Now I want to return all strings from list A which have all keywords from B in it as a new list.

def string_search(strings, keys):
    res = []
    for s in strings:
        full = True
        for k in keys:
            if not(k in s):
                full = False
        if full == True:
    return res

In which way could I improve this code? I ask purely out of curiosity, since it works perfectly fine and it is not the bottleneck of my processing chain.


Your general coding style is very readable. You stick to PEP8 and your function and the variables are named reasonably. You could optimize your code by using the built-in functions filter and all:

def string_search(strings, keys):
    return filter(lambda string: all(key in string for key in keys), strings)

Also do not use if var == True: but if var: instead.

| improve this answer | |
  • \$\begingroup\$ Great Point. Most times I use lists which are iteratively filled and then returned. It seems that using Generator functions generally is better. would you say so? (If yes, then I learned something today. If no, please provide an example) \$\endgroup\$ – Nikolas Rieble Nov 18 '16 at 9:33
  • 3
    \$\begingroup\$ That depends on what you want to do with the iterable in general. Generators play off especially if you have a lot of items that you only need to read once. I personally tend to use generators when returning iterables from functions and, if I need to read the values multiple times, convert them, using list(generator). \$\endgroup\$ – Richard Neumann Nov 18 '16 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.