Ad space (banner)
🐍Python Lessons
Lesson 24 / 69

Transforming a List with map()

This lesson covers Python's map() function, so you can transform every element of a list at once. It's written for anyone searching "Python map tutorial" or "Python map vs list comprehension".

map(function, list) applies the same operation to every element of a list, producing a new map object. Think of it like a conveyor belt machine — every item that passes through gets processed the same way. Wrap the result in list() to turn it into a regular list.

The sample code passes an anonymous function (a lambda expression), lambda n: n * 2, to map(), building doubled, where every element of nums has been doubled. Notice in the output that the original nums list is left unchanged.

A common beginner mistake is expecting the result of map() to display as a list on its own. A map object uses "lazy evaluation" — its contents aren't finalized until converted to a list — so you need to wrap it in list(). The same thing can also be written as a list comprehension, and Python developers are somewhat split on which they prefer.

Being comfortable reading both makes it easier to understand other people's code. In practice, list comprehensions tend to be favored for simple transformations, while map is often preferred when applying an existing function as-is.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)