2
input_list =  ['soap','sharp','shy','silent','ship','summer','sheep']

Extract a list of names that start with an s and end with a p (both 's' and 'p' are lowercase) in input_list using filter function.

Output should be:

['soap', 'sharp', 'ship', 'sheep']
a_guest
  • 34,165
  • 12
  • 64
  • 118
Ali Bawazeer
  • 29
  • 1
  • 2

7 Answers7

2
input_list = ['soap', 'sharp', 'shy', 'silent', 'ship', 'summer', 'sheep']

sp = list(filter(lambda x: x[0] == 's' and x[-1]=='p', input_list))

print(sp)
Paul Bissex
  • 1,611
  • 1
  • 17
  • 22
  • An alternative to the second line that some might find a little more readable: ```sp = [w for w in input_list if w.startswith('s') and w.endswith('p')]``` – Paul Bissex Jun 02 '21 at 16:40
2

sp = list(filter(lambda x: x.startswith("s") and x.endswith("p"), input_list))

print(sp)

This would give you the correct answer

1

Here how's it can be done easily-

input_list =  ['soap','sharp','shy','silent','ship','summer','sheep']


def fil_func(name):
    if name[0]=='s' and name[-1]=='p':
        return True

correct_name = []
for i in input_list:
    name = list(filter(fil_func, input_list)) # list() is added because filter function returns a generator.
print(name)
Pankaj Mishra
  • 445
  • 6
  • 15
0

Here you go:

list(filter(lambda x: x.startswith("s") and x.endswith("p"), input_list))
DavideBrex
  • 2,374
  • 1
  • 10
  • 23
0
sp = list(filter(lambda x:x[0]=='s' and x[-1]=='p',input_list))


print(sp)
4b0
  • 21,981
  • 30
  • 95
  • 142
0
sp = list(filter(lambda word: (word[0]=="s") and (word[-1]=="p"), input_list))
Raj Mehta
  • 93
  • 2
  • 9
-1

It can easily be done using the following code sample:

input_list =  ['soap','sharp','shy','silent','ship','summer','sheep']

sp = list(filter(lambda x:x[0]=='s' and x[-1]=='p', input_list)) 

print(sp) 
surajs1n
  • 1,493
  • 6
  • 23
  • 34
  • Best not to copy answers. There is already one just like this one here: https://stackoverflow.com/a/66231324/11603043 – Axisnix May 16 '21 at 10:03