How do I map lists in Python in pure Python?

In Python, you can map lists using the built-in `map()` function or list comprehensions. The `map()` function applies a specified function to each item in the given iterable (like a list) and returns a map object (which is an iterator). To convert it back to a list, you can use the `list()` function.

Using `map()` Function

The syntax for the `map()` function is:

map(function, iterable)

Here's an example that doubles each number in the given list:

numbers = [1, 2, 3, 4, 5] doubled = list(map(lambda x: x * 2, numbers)) print(doubled) # Output: [2, 4, 6, 8, 10]

Using List Comprehension

You can also use a list comprehension to achieve the same result:

numbers = [1, 2, 3, 4, 5] doubled = [x * 2 for x in numbers] print(doubled) # Output: [2, 4, 6, 8, 10]

Python map function list comprehension iterable lambda programming code examples