1

I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])

it seems that it should work but its giving syntax error

What is the issue here?

4
  • What do you expect to happen on the pass branch? Note that map converts every input element to an output element. It cannot remove elements. Commented Feb 17, 2020 at 12:05
  • 2
    My usual reminder: If you need a lambda to use map or filter, don't. It'll be slower and less readable than an equivalent list comprehension/generator expression that avoids a lambda by inlining the same logic. Commented Feb 17, 2020 at 12:11
  • @ShadowRanger can you give me an example? Commented Feb 18, 2020 at 3:16
  • @rahulKushwaha: Example of what? Your answers already show the options (map/filter, listcomp, genexpr). Commented Feb 18, 2020 at 12:02

5 Answers 5

2

You probably need filter here and use lambda x : x == "apple".

Ex:

l = list(filter(lambda x : x == "apple", ['apple', 'banana', 'cherry']))
print(l)
Sign up to request clarification or add additional context in comments.

1 Comment

or a list comprehension: l = [x for x in input if predicate(x)]
2

you need this:

[x for x in ['apple', 'banana', 'cherry'] if x == "apple"]

Comments

1

pass is not a value, so you can't use it in an expression. You could use None, but then you end up with ['apple', None, None] rather than just ['apple'], so you have to filter the Nones like this:

l = filter(lambda x: x is not None, map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry']))

A cleaner solution would be to use list comprehension:

l = [ x for x in ['apple', 'banana', 'cherry'] if x == 'apple' ]

Comments

1

Depending on size of your list it might be better to use generator rather than list comprehension, that is:

l = (x for x in ['apple', 'banana', 'cherry'] if x=='apple')

generally list comprehensions will lead to bigger memory usage, than equivalent generators, though for small sizes difference might be neglible.

Comments

0

you are not allowed to use pass keyword in conditional expressions(ternary operator)

you can read more about conditional expressions in PEP308

So, if you want to use the map built-in function you have to pick an "else" value for the ternary operator, ex:

map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry'])

or if you want to filter your list by the string "apple" you can use @Rakesh suggested solution by using the built-in function filter:

list(filter(lambda x : x == "apple", ['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.