Save items starting with 'S' from list l to l2 using Python

Viewed 119

I need to save all the list items starting with 'S' from list l to l2

l= ['Santa Cruz','Santa fe','Sumbai','Delhi']
l1 = []
l1 = list(map(lambda x : x if x[0] == 'S',l))
print(l1)

Above has resulted in an syntax error.

I tried Trial-I

l= ['Santa Cruz','Santa fe','Sumbai','Delhi']
l1 = []
l1 = list(map(lambda x : x if x[0] == 'S' else '',l))
l1

and it returns [True, True, True, False]

my expected output is ['Santa Cruz','Santa fe','Sumbai']

Trial-II

l= ['Santa Cruz','Santa fe','Sumbai','Delhi']
l1 = []
l1 = list(map(lambda x : x[0] == 'S',l))
print(l1)

Trial-II returned ['Santa Cruz','Santa fe','Sumbai', '']

my expected result should not have the blank list item in the ending.

4 Answers
l= ['Santa Cruz','Santa fe','Sumbai','Delhi']
l1 = [name for name in l if name.startswith("S")]

Edit

All strings have a method called startswith. Taking the 0th element of the string would also have done the trick.

For list comprehensions, what is going on in the line l1 = [name for name in l if name.startswith("S")] is basically the same as

l= ['Santa Cruz','Santa fe','Sumbai','Delhi']
l1 = []

for name in l:
    if name.startswith("S"): # also: if name[0] == "S" would work
        l1.append(name)

But a more consise way of writing it down

This should do the trick

 [x for x in l if x[0] == 'S']

You can not use if without else inside lambda. If you want to use lambda necessarily, you can use filter instead of map:

l1=list(filter(lambda x: x[0] == 'S', l))

>>> print(l1)

['Santa Cruz', 'Santa fe', 'Sumbai']

If you want to count the words starting with 'S' using Map function, as per your comment, you can do the following:

result=sum(list(map(lambda x : 1 if x[0] == 'S' else 0,l)))

>>> print(result)

3

Using list comprehension: this means, append each element x in l to l1 if the 0th element in x is the string "S".

l1 = [x for x in l if x[0] == 'S']
Related