0

I am trying to solve a class assignment as listed below

Use lambda expressions and the filter() function to filter out words from a list that don't start with the letter 's'. For example:

seq = ['soup','dog','salad','cat','great']

should be filtered down to:

['soup','salad'] 

I wrote the following two sets of code...

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

seq = ['soup', 'dog','salad', 'cat', 'great']
def checkf (input):
    if input[0]=='s':
            a = "TRUE"
    return(a)
test = seq[0]
result = filter (checkf(test),seq)
print (result)

Both codes give a strange answer filter object at 0x112aa06d8 as if it is returning a memory address in hexadecimal... What's wrong?

5

3 Answers 3

3

In python 3, filter objects are iterators. To print the contents, you have to materialize it into a sequence first, so try:

print( list(result))

See also: How to use filter, map, and reduce in Python 3

Sign up to request clarification or add additional context in comments.

Comments

0

To use lambda and filter to resolve this problem, you need to specify that the result of your code will be a list.

So the following will work:

seq = ['soup', 'dog','salad', 'cat', 'great']
list(filter (lambda test: test[0] == "s",seq))

or (assigning to an object):

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

The result of the two codes will be:

['soup', 'salad']

Comments

0

This is the below code where your seq can be solved according to the lambda function.

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

output: ['soup', 'salad']

using it in a function

seq = ['soup', 'dog','salad', 'cat', 'great']
def check(input):
    result = list(filter (lambda test: test[0] == "s",seq))
    return result

check(seq)

output: ['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.