5
\$\begingroup\$

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
                break
        if full == True:
            res.append(s)
    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.

\$\endgroup\$
0

1 Answer 1

6
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\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\$ Commented Nov 18, 2016 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\$ Commented Nov 18, 2016 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.