Using startswith in lambda expression and filter function with Python

Question:

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

Asked By: bkullukcu

||

Answers:

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']
Answered By: Thavas Antonio

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

filtered = lambda x: x.startswith('s')
Answered By: Sayse

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
Answered By: Shivam Roy
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.