Search code examples
pythonlistfunctionfilterlambda

Using startswith in lambda expression and filter function with Python


I'm trying to find the words starting with character "s". I have a list of strings (seq) to check.

seq = ['soup','dog','salad','cat','great']

sseq = " ".join(seq)

filtered = lambda x: True if sseq.startswith('s') else False

filtered_list = filter(filtered, seq)

print('Words are:')
for a in filtered_list:
    print(a)

The output is:

Words are:
soup
dog
salad
cat
great

Where I see the entire list. How can I use lambda and filter() method to return the words starting with "s" ? Thank you


Solution

  • Your filter lambda always just checks what your joined word starts with, not the letter you pass in.

    filtered = lambda x: x.startswith('s')