0

I have a list like,

old_list=["a_apple","b_banana","c_cherry"]

and I want to get new list using lambda.

new_list=["apple","banana","cherry"]

I tried but it doesn't work as I expected. here is what I wrote.

new_list=filter(lambda x: x.split("_")[1], old_list)

what is the problem ?

1
  • 3
    Try to use map instead of filter Commented Nov 29, 2018 at 7:25

4 Answers 4

2

Try this:

Python-2:

In [978]: old_list=["a_apple","b_banana","c_cherry"]

In [980]: new_list = map(lambda x: x.split("_")[1], old_list)

In [981]: new_list
Out[981]: ['apple', 'banana', 'cherry']

Python-3:

In [4]: new_list = list(map(lambda x: x.split("_")[1], old_list))

In [5]: new_list
Out[5]: ['apple', 'banana', 'cherry']
Sign up to request clarification or add additional context in comments.

Comments

1

You can map the list with a lambda function:

list(map(lambda s: s.split('_')[1], old_list))

This returns:

['apple', 'banana', 'cherry']

Comments

1

Using list comprehensions

lst=["a_apple","b_banana","c_cherry"]
[i.split("_")[1] for i in lst]

Output:

['apple', 'banana', 'cherry']

Comments

0

By using lambda and map:

li=["a_apple","b_banana","c_cherry"]

new_li = map(lambda x: x.split('_')[1], li)
print (list(new_li))
# ['apple', 'banana', 'cherry']

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.