Maps in Python

Python tutorial · PySpark.in

Map

The map() function in Python is a built-in tool used to apply a function to every item of a list, tuple, or any iterable.

Syntax

PLAINTEXT
1map(function, iterable)
▶ Output will appear here.

1. Basic Example

Convert all numbers to double

Uses map() with a lambda to transform each number in the list.

PYTHON
1numbers = [1, 2, 3, 4]
2result = map(lambda x: x * 2, numbers)
3print(list(result))
▶ Output will appear here.

2. Using map() with a normal function

Applies a user-defined function to all items of an iterable.

PYTHON
1def square(n):
2 return n * n
3nums = [1, 2, 3, 4]
4result = map(square, nums)
5print(list(result))
▶ Output will appear here.

3. map() with Two lists

Applies a function to each element of a tuple just like lists.

Example

Add two lists element-wise

PYTHON
1a = [10, 20, 30]
2b = [1, 2, 3]
3result = map(lambda x, y: x + y, a, b)
4print(list(result))
▶ Output will appear here.

4. map() with strings

Applies a function (like str.upper,str.lower) to each string in a list.

Convert each word to uppercase

PYTHON
1words = ["hello", "python", "megha"]
2result = map(str.upper, words)
3print(list(result))
▶ Output will appear here.

5. map() with multiple data types

Converts each element of a list into another type (e.g., numbers to strings).

Convert list of numbers → strings

PYTHON
1nums = [10, 20, 30]
2result = map(str, nums)
3print(list(result))
▶ Output will appear here.

6. map() with Tuples

Applies a function to each element of a tuple just like lists.

map() works with any iterable, including tuples.

PYTHON
1t = (2, 4, 6)
2result = map(lambda x: x * 5, t)
3print(list(result))
▶ Output will appear here.

7. map() vs for loop (why map() is better)

map() provides a shorter and cleaner alternative to loops for transforming iterables.

Using a loop:

PYTHON
1nums = [1, 2, 3]
2new_list = []
3for n in nums:
4 new_list.append(n * 2)
5print(new_list)
▶ Output will appear here.

Using map():

PYTHON
1nums = [1, 2, 3]
2result = map(lambda x: x * 2, nums)
3print(list(result))
▶ Output will appear here.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges