0

For a recent Python homework assignment, we were assigned to create a function that would return words in a list that start with 'd'. Here's the relevant code:

def filter_words(word_list, letter):
'''
INPUT: list of words, string
OUTPUT: list of words

Return the words from word_list which start with the given letter.

Example:
>>> filter_words(["salumeria", "dandelion", "yamo", "doc loi", "rosamunde",
                  "beretta", "ike's", "delfina"], "d")
['dandelion', 'doc loi', 'delfina']
'''

letter_list = []
for word in word_list:
        if word[0] == letter:
            letter_list.append(word)
return letter_list

The above nested if statement that I wrote works when I run the code, which I'm happy about (:D); however, in trying to become more pythonic and astute with the language, I found a very helpful article on why Lambda functions are useful and how to possibly solve this same challenge with a lambda, but I couldn't figure out how to make it work in this case.

I'm asking for guidance on how to potentially write my above nested if statement as a lambda function.

1
  • [(lambda x: x)(word) for word in (lambda x: x)(letter_list) if (lambda x, y, z: x[y] == z)(word, x, letter)] Commented Jun 23, 2016 at 23:31

2 Answers 2

6

In a way, the lambda equivalent of your if condition would be:

fn = lambda x: x[0] == 'd'  #fn("dog") => True, fn("test") => False

Further, you can use .startswith(..) instead of comparing [0]. It then becomes something like:

letter_list = filter(lambda x: x.startswith('d'), word_list)

But more pythonic is:

letter_list = [x for x in word_list if x.startswith('d')]
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure what you're asking, because changing the if into a lambda of some sort doesn't seem to be useful. You neglected to post your failed code so we'd know what you want.

However, there is a succinct way to express what you're doing:

def filter_words(word_list, letter):
    return [word in letter_list if word[0] == letter]

Comments

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.