How can you use the map function in Python to execute a statement in a lambda for each item?

Print statement in lambda is not executed by the map function.

In javascript, you can use the map method to execute a statement in a lambda like this:

let names = ["Vera", "Chuck", "Dave"];
names.map(x => console.log(x));

Output:

Vera
Chuck
Dave

In C# you can do the same with the LINQ Select method.

var names = List<string>{ "Vera", "Chuck", "Dave" };
names.Select(x => Debug.WriteLine(x));

Output:

Vera
Chuck
Dave

Map the list to execute a statement in a lambda in Python

When map executes a statement in a lambda in Python, you notice there is no output.

names = ["Vera", "Chuck", "Dave"]
map(lambda x: print(x), names)

Output:

The reason for this is that the map function returns a map object, which is a generator object. To get the elements, you have to iterate over them or convert to a list.

Let’s convert to a list:

names = ["Vera", "Chuck", "Dave"]
list(map(lambda x: print(x), names))

Output:

Vera
Chuck
Dave

Now the print statement is executed for each element in the list.

Do not use the map function to execute a statement without a result.

You have seen that it is possible to put a statement in a lambda and use the lambda in combination with map. But is it a good idea? Not in this case. Map is a morphing function to transform a list to another list. Not for the purpose to execute stuff and not return. Look what happens if you print the result of the mapping:

names = ["Vera", "Chuck", "Dave"]
print(list(map(lambda x: print(x), names)))

Output:

Vera
Chuck
Dave
[None, None, None]

We have (mis)used the map function to process each element in the list and ignore the result.

If processing elements and ignore the result is what you want, there is already a great way to do that. It’s called the for loop!

names = ["Vera", "Chuck", "Dave"]
for n in names:
print(n)

Output:

Vera
Chuck
Dave

If it didn’t work in Python, then why did it work in javascript and C#?

Apparently javascript and C# execute the lambda even if the result is not evaluated but that does not mean it is a good idea to use map for the purpose to for-each. If you want to process each item in a list, use:

for-of in Javascript:

for (const n of names) {
}

foreach in C#:

foreach (var n in names) {
}
Written by Loek van den Ouweland on 2020-12-07.
Questions regarding this artice? You can send them to the address below.