The main problem with your code example is that you can only return from a function once, at which point the function stops executing. This is why your function returns only one value.
If you wish to return multiple values you must return a container object like a list or a set. Here's how your code might look if you use a list:
def find(string_list, search):
letters = set(search)
result = [] # create an empty list
for word in string_list:
if letters & set(word):
# append the word to the end of the list
result.append(word)
return result
The if test here is actually not doing quite what your problem statement called for. Since a set is an unordered collection, the & operation can test only if the two sets have any elements in common, not that they appear in the same order as the input. For example:
>>> letters = set("hello")
>>> word = set("olleh")
>>> word & letters
set(['h', 'e', 'l', 'o'])
As you can see, the operator is returning a set whose elements are those that are common between the two sets. Since a set is True if it contains any elements at all, this is actually testing whether all of the letters in the search string appear in a given item, not that they appear together in the given order.
A better approach is to test the strings directly using the in operator, which (when applied to strings) tests if one string is a substring of another, in sequence:
def find(string_list, search):
result = []
for word in string_list:
if search in word:
result.append(word)
return result
Since this pattern of iterating over every item in a list and doing a test on it is so common, Python provides a shorter way to write this called a list comprehension, which allows you to do this whole thing in one expression:
def find(string_list, search):
return [word for word in string_list if search in word]
This executes just as the prior example but is more concise.
filter. Advanced hint: anythingfiltercan do, list comprehensions can do.