0

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

7
  • 2
    Why not just use a simple list comprehension? After all, Python is all about doing things simply. :-) Commented May 14, 2021 at 18:41
  • [word for word in seq if word.lower().startswith('s')] Commented May 14, 2021 at 18:42
  • Why does filtered ignore its argument? Commented May 14, 2021 at 18:43
  • 1
    Why are you using sseq in the function, instead of x, the argument? Why are you creating sseq in the first place? Commented May 14, 2021 at 18:44
  • 2
    Also, as an aside, don't assign lambda expressions to a name. If you are going to do that, just use a full function definition Commented May 14, 2021 at 18:44

3 Answers 3

5

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

filtered = lambda x: x.startswith('s')
Sign up to request clarification or add additional context in comments.

Comments

1

Try this.

seq = ['soup','dog','salad','cat','great']
result = list(filter(lambda x: (x[0] == 's'), seq)) 
print(result)

or

seq = ['soup','dog','salad','cat','great']
result = list(filter(lambda x: x.startswith('s'),seq))
print(result)

both output

['soup', 'salad']

Comments

0

This is another elegant method if you're okay with not using filter:

filtered_list = [x for x in seq if x.startswith('s')]
print('Words are: '+ " , ".join(filtered_list))

Output:

Words are: soup , salad

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.