1. Python style guide recommends using list comprehensions instead of map/reduce
  2. String formatting using percent operator is obsolete, consider using format() method
  3. the code you need is this simple one-liner

    output = [" this string contains {} and {}".format(x, y) for (x, y) in matrix]

Answer from Arseniy on Stack Overflow
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-map-lambda.html
Python Map Lambda
Therefore, the examples wrap the map() result in list() for printing. >>> nums = [1, 2, 3, 4, 5] >>> >>> map(lambda n: 2 * n, nums) # print fails, so list() below <map object at 0x10ce142e8> >>> >>> list(map(lambda n: 2 * n, nums)) # e.g.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-map-with-lambda
Python map with Lambda - GeeksforGeeks
July 23, 2025 - We pass the lambda function and the list to map(), and it applies the function to each item and square each element in a list.
๐ŸŒ
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.
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.

๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Apply a Function to Items of a List in Python: map() | note.nkmk.me
May 15, 2023 - In Python, you can use map() to apply built-in functions, lambda expressions (lambda), functions defined with def, etc., to all items of iterables, such as lists and tuples. Built-in Functions - map() ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ lambda-functions-in-python
Lambda Functions in Python โ€“ How to Use Lambdas with Map, Filter, and Reduce
June 14, 2024 - The map function applies a specified function to each item in an iterable (like a list) and returns a new iterable with the updated items. ... # List of pairs of numbers pairs = [(2, 3), (4, 5), (6, 7)] # Using lambda function with map to multiply ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-lambda-anonymous-functions-filter-map-reduce
Python Lambda Functions - GeeksforGeeks
The function is called with a lambda function and a new list is returned which contains all the lambda-modified items returned by that function for each item. ... The lambda function doubles each number. map() iterates through a and applies ...
Published ย  December 11, 2024
๐ŸŒ
Reddit
reddit.com โ€บ r/pythontips โ€บ unleashing the power of lambda functions in python: map, filter, reduce
r/pythontips on Reddit: Unleashing the Power of Lambda Functions in Python: Map, Filter, Reduce
July 22, 2023 -

Hello Pythonistas!

I've been on a Python journey recently, and I've found myself fascinated by the power and flexibility of Lambda functions. These anonymous functions have not only made my code more efficient and concise, but they've also opened up a new way of thinking about data manipulation when used with Python's built-in functions like Map, Filter, and Reduce.

Lambda functions are incredibly versatile. They can take any number of arguments, but can only have one expression. This makes them perfect for small, one-time-use functions that you don't want to give a name.

Here's a simple example of a Lambda function that squares a number:

square = lambda x: x ** 2

print(square(5)) # Output: 25

But the real power of Lambda functions comes when you use them with functions like Map, Filter, and Reduce. For instance, you can use a Lambda function with `map()` to square all numbers in a list:

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x ** 2, numbers))

print(squared) # Output: [1, 4, 9, 16, 25]

You can also use a Lambda function with `filter()` to get all the even numbers from a list:

numbers = [1, 2, 3, 4, 5]

even = list(filter(lambda x: x % 2 == 0, numbers))

print(even) # Output: [2, 4]

And finally, you can use a Lambda function with `reduce()` to get the product of all numbers in a list:

from functools import reduce

numbers = [1, 2, 3, 4, 5]

product = reduce(lambda x, y: x * y, numbers)

print(product) # Output: 120

Understanding and using Lambda functions, especially in conjunction with Map, Filter, and Reduce, has significantly improved my data manipulation skills in Python. If you haven't explored Lambda functions yet, I highly recommend giving them a try!

Happy coding!

๐ŸŒ
Python.org
discuss.python.org โ€บ python help
The map() function or the list comprehension? - Python Help - Discussions on Python.org
September 12, 2023 - There are two ways to apply a function to each element of an iterated object in python: the map function: >>> lst = [1, 2, 3, 4] >>> list(map(str, lst)) ['1', '2', '3', '4'] >>> list(map(lambda a: a + 1, lst)) [2, 3, 4, 5] the list comprehension: ...
๐ŸŒ
Python Course
python-course.eu โ€บ advanced-python โ€บ lambda-filter-reduce-map.php
4. Lambda Operator, filter, reduce and map | Advanced
I've not had the time to follow the most recent rounds, but I propose that we keep lambda, so as to stop wasting everybody's talent and time on an impossible quest." We can see the result: lambda, map() and filter() are still part of core Python. Only reduce() had to go; it moved into the module functools. ... There is an equally powerful alternative to lambda, filter, map and reduce, i.e. list comprehension
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-map
Python map() | Function Guide (With Examples)
February 6, 2024 - The map function applies this lambda function to the corresponding items in numbers1 and numbers2. The map function is not limited to simple functions like addition or squaring. You can use complex functions as well, including functions that ...
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ python-map-function
Python map() Function (With Examples)
The map() function passes each element in the list to the built-in functions, a lambda function, or a user-defined function, and returns the mapped object.
๐ŸŒ
Enki
enki.com โ€บ post โ€บ apply-a-function-to-each-element-in-a-list---python-s-map-function
Enki | Blog - Apply a Function to Each Element in a List - Pythonโ€™s map function
In this example, map() applies the square function to every number in the list. The result shows how you can transform all list elements effortlessly. Lambda functions in Python offer a way to create small anonymous functions on the go.
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ lambda-map-and-filter-in-python-4935f248593
Lambda, Map, and Filter in Python | by Rupesh Mishra | Better ...
March 19, 2023 - We can pass multiple sequences to the map functions as shown below: Here, each i^th element of list_a and list_b will be passed as an argument to the lambda function. In Python3, the map function returns an iterator or map object which gets lazily evaluated, similar to how the zip function ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-map-function
Python map() function - GeeksforGeeks
In this example, we use map() to extract the first character from each string in a list. ... Explanation: The lambda function s: s[0] extracts the first character from each string in the list words.
Published ย  October 23, 2024
Top answer
1 of 2
6

Why? What am I missing? I understand map returns an iterator which is supposed to save memory instead of just holding the entire list right away. But when is my super heavy print function going to be triggered then?

The map function is what's commonly known in programmer terminology as lazy. It won't do any work unless it has to. This is more broadly known as in functional programming as lazy evaluation. Rather than immediately compute any values, the map function instead returns what's known as an iterator. By doing this, it's delegating the job of compute the values it was given back to you.

A single value can be computed by the iterator using next:

>>> arr = [1, 2, 3]
>>> it = map(lambda x: print(x), arr)
>>> next(it)
1
>>> 

However, when you casted the map iterator to be a list, you were forcing map to compute all of its values and thus call your function:

>>> it = map(lambda x: print(x), arr)
>>> list(it)
1
2
3
4
[None, None, None, None]
>>> 
2 of 2
3

As you said, you have to switch your mindset to use functional programming. One of the key concepts of functional programming is lazy evaluation, which is the default policy in languages such as Haskell.

The purpose of this policy is to save both time and memory, by calculating something only when it is needed. In that sense Python generators are also close to the functional paradigm.

If you want to execute it as soon as possible, you shouldn't write it in a functional style and fix it with list() if you don't care about the results. Using a loop is totally ok.

๐ŸŒ
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.
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ python basics โ€บ how to transform list elements with python map() function
How to Transform List Elements with Python map() Function
March 26, 2025 - bonuses = [100, 200, 300] iterator = map(lambda bonus: bonus*2, bonuses)Code language: Python (python) Once you have an iterator, you can iterate over the new elements using a for loop. Or you can convert an iterator to a list by using the the list() function: