Question: Write a function called starts_with(prefix, wordlist) that takes as inputs a string prefix and a list of strings wordlist, and that uses a list comprehension
Write a function called starts_with(prefix, wordlist) that takes as inputs a string prefix and a list of strings wordlist, and that uses a list comprehension to return a list consisting of all words from wordlist that begin with prefix. For example:
>>> starts_with('fun', ['functions', 'are', 'really', 'fun!']) result: ['functions', 'fun!'] >>> starts_with('on', ['only', 'functions', 'on', 'the', 'brain']) result: ['only', 'on'] # note that 'functions' is *not* included >>> names = ['Alex', 'Adlai', 'Alison', 'Amalia', 'Anbita'] >>> starts_with('A', names) result: ['Alex', 'Adlai', 'Alison', 'Amalia', 'Anbita'] >>> starts_with('Al', names) result: ['Alex', 'Alison'] >>> starts_with('D', names) result: [] Hints:
-
Your list comprehension will need an if clause.
-
Make sure that you only include words that start with the specified prefix. For instance, in the second example above, the string 'functions' is not included in the return value, because the string 'on' is in the middle of 'functions', rather than at the start. As a result, you wont be able to use the in operator to test for the presence of the prefix in a word.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
