You'll have to wrap the map around a filter around the list:

example_map = map(lambda x: x*2, filter(lambda x: x*2/6. != 1, range(5)))
Answer from jwodder on Stack Overflow
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-map-lambda.html
Python Map Lambda
The code of the lambda is typically ... or if-statements, and does not use "return". Lambda is perfect where you have a short computation to write inline. Many programs have some sub-part which can be solved very compactly this way. For longer code, def is better. The map() function ...
Discussions

python - using a conditional and lambda in map - Stack Overflow
5 ValueError while applying lambda expression to elements of an array · 2 For loop to replace value in one dataframe with X if it appears in another dataframe · 13 How to map a series of conditions as keys in a dictionary? 10 python map function (+ lambda) involving conditionals (if) More on stackoverflow.com
🌐 stackoverflow.com
Is there a way to perform "if" in python's lambda? - Stack Overflow
This is valid in Python 3.x, but ... 2.6. In Python 2.x this answer does not work, since you can't use print in a lambda expression. 2021-11-21T11:46:06.623Z+00:00 ... Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases. a = ''.join(map(lambda x: ... More on stackoverflow.com
🌐 stackoverflow.com
dictionary - Python - How to use map function and lambda function with if condition - Stack Overflow
I want to compare the wordlist and the checklist by using map function and lambda function if the words in wordlist and checklist. this words will be deleted in wordlist. Anyone can help me? thanks... More on stackoverflow.com
🌐 stackoverflow.com
pandas - Map an if statement in Python - Stack Overflow
I'm trying to map the following function over a pandas dataframe (basically a list) in python 2.7: df["Cherbourg"] = df["Embarked"].map(lambda x: if (x == "C") 1 else 0) But python errors saying u... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-lambda-anonymous-functions-filter-map-reduce
Python Lambda Functions - GeeksforGeeks
The lambda function checks if a number is even (x % 2 == 0). filter() applies this condition to each element in nums. map() function applies a lambda expression to each element of a list and returns a new list with the transformed values.
Published   4 days ago
🌐
YouTube
youtube.com › watch
Python Lambda If Else Statements with Map() - TUTORIAL - YouTube
Python tutorial on how to use if/else statements in a lambda function with map().💻 Python List Comprehensions Course Playlist:https://www.youtube.com/playli...
Published   January 2, 2021
🌐
Code Maven
code-maven.com › slides › python › map-with-lambda-with-condition
map with lambda with condition
February 4, 2024 - numbers = [1, 2, 3, 4] a = map(lambda n: 2*n if n % 2 else n, numbers) print(a) # [2, 2, 6, 4] Index (i) Table of Contents (t) Indexed keywords (k) Chapter TOC (d) Hide/Show (h) Copyright 2024 Gábor Szabó ·
Find elsewhere
🌐
Teclado
teclado.com › 30-days-of-python › python-30-day-20-map-filter
Day 20: map, filter, and Conditional Comprehensions | Teclado
1) Use map to call the strip method on each string in the following list: humpty_dumpty = [ " Humpty Dumpty sat on a wall, ", "Humpty Dumpty had a great fall; ", " All the king's horses and all the king's men ", " Couldn't put Humpty together again." ] Print the lines of the nursery rhyme on different lines in the console. Remember that you can use the operator module and the methodcaller function instead of a lambda expression if you want to.
🌐
Real Python
realpython.com › python-lambda
How to Use Python Lambda Functions – Real Python
December 1, 2023 - As an example, if you wanted to transform a list of strings to a new list with each string capitalized, you could use map(), as follows: ... You need to invoke list() to convert the iterator returned by map() into an expanded list that can be displayed in the Python shell interpreter. Using a list comprehension eliminates the need for defining and invoking the lambda function:
🌐
Python Tips
book.pythontips.com › en › latest › map_filter.html
4. Map, Filter and Reduce — Python Tips 0.1 documentation
def multiply(x): return (x*x) def add(x): return (x+x) funcs = [multiply, add] for i in range(5): value = list(map(lambda x: x(i), funcs)) print(value) # Output: # [0, 0] # [1, 2] # [4, 4] # [9, 6] # [16, 8] As the name suggests, filter creates a list of elements for which a function returns true. Here is a short and concise example: number_list = range(-5, 5) less_than_zero = list(filter(lambda x: x < 0, number_list)) print(less_than_zero) # Output: [-5, -4, -3, -2, -1] The filter resembles a for loop but it is a builtin function and faster. Note: If map & filter do not appear beautiful to you then you can read about list/dict/tuple comprehensions.
🌐
CodeRivers
coderivers.org › blog › python-lambda-if-condition
Python Lambda with If Condition: A Comprehensive Guide - CodeRivers
April 13, 2025 - This lambda function has multiple ... in Python applies a given function to all items in an iterable. When used with a lambda function containing an if condition, it can transform elements based on a condition....
Top answer
1 of 2
15

because the lambda function needs to be created len(data) times, thus inefficient.

Not true, in the example the lambda definition is evaluated only once at compile time and not len(data) times - there is no need to assign it to a name for performance reasons. Look at Sergey's answer, he proves lambda is not expensive at all for this case.

If you do want to give it a name for the sake of clarity, you should just use a def statement instead. Assigning a lambda to a name is considered bad style: according to PEP-8 Programming Recommendations you should "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier". Quoting from the official style guide:

Yes:

def f(x): return 2*x

No:

f = lambda x: 2*x:

The only difference between lambda and the one-line def is that def will give it a name (probably an extra LOAD_CONST):

>>> import dis

>>> def _(x):
        return f(x, 30)

>>> dis.dis(_)
  2           0 LOAD_GLOBAL              0 (f)
              2 LOAD_FAST                0 (x)
              4 LOAD_CONST               1 (30)
              6 CALL_FUNCTION            2
              8 RETURN_VALUE

>>> dis.dis(lambda x: f(x, 30))
  1           0 LOAD_GLOBAL              0 (f)
              2 LOAD_FAST                0 (x)
              4 LOAD_CONST               1 (30)
              6 CALL_FUNCTION            2
              8 RETURN_VALUE

As you can see above, both forms compile to the same bytecode.

The lisp inspired functions map, filter and reduce always felt a bit alien in Python. Since the introduction of list comprehensions (at version 2.0 IINM) they became the idiomatic way to achieve the same result. So this:

new_data = map(lambda x: f(x, 30), data)

Is often written as:

new_data = [f(x, 30) for x in data]

If data is big and you are just iterating over it, generator expressions trade memory for cpu:

for value in (f(x, 30) for x in data):
    do_something_with(value)

The lispy constructs like map, filter and reduce are likely to be retired (moved to the functools module) and I recommend the use of list comprehensions and generator expressions in new code.

Last, Python is surprisingly counterintuitive regarding performance. You should always profile in order to put your beliefs about performance in check.

Bottom line: never worry about "optimizing" a damn thing until you have profiled it and know for sure it's a relevant bottleneck.

2 of 2
4

Lambda creates only once when map calls

In [20]: l = list(range(100000))

In [21]: %timeit list(map(lambda x: x * 2, l))
100 loops, best of 3: 13.8 ms per loop

In [22]: g = lambda x: x * 2

In [23]: %timeit list(map(g, l))
100 loops, best of 3: 13.8 ms per loop

As you can see, the execution time is not changed.

🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python map() with lambda function
Python map() with Lambda Function - Spark By {Examples}
May 31, 2024 - In this example, the lambda function takes one argument x and returns its square. The map() function applies this python lambda function to each item of the numbers list, and the result is a new iterator containing the squared values of each number.
🌐
Medium
medium.com › towards-data-science › understanding-the-use-of-lambda-expressions-map-and-filter-in-python-5e03e4b18d09
Python’s Lambda Expressions, Map and Filter | by Luciano Strika | TDS Archive | Medium
July 21, 2022 - That basically means it will generate a sequence that’s lazily evaluated, can be iterated on and must be cast into a list in order to be sliced or indexed. On the other hand, map returns a normal list in Python 2.7. So that’s where lambdas and maps make a sort of synergy: As fluid as writing a line using map can be, it can become even more fluid if you can invent your small function on the fly.
🌐
Analytics Vidhya
analyticsvidhya.com › home › lambda functions in python | map, filter, and reduce
Lambda Functions in Python | Map, Filter, and Reduce - Analytics Vidhya
March 22, 2022 - lst = [2,4,6,8] #find largest element print(reduce(lambda x, y: x if x>y else y, lst)) #find smallest element print(reduce(lambda x, y: x if x<y else y, lst)) List comprehension is nothing but a for loop to append each item in a new list to create a new list from an existing index or a set of elements. The work we have performed using Map, filter, and reduce can also be done using List Comprehension.