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.
- Transforms each element of an iterable
- Returns a map object (convert to list/tuple to see output)
- Faster & cleaner than loops
- Wroks with lists, tuples, sets, strings, and multiple iterables
Syntax
1. Basic Example
Convert all numbers to double
Uses map() with a lambda to transform each number in the list.
2. Using map() with a normal function
Applies a user-defined function to all items of an iterable.
3. map() with Two lists
Applies a function to each element of a tuple just like lists.
Example
Add two lists element-wise
4. map() with strings
Applies a function (like str.upper,str.lower) to each string in a list.
Convert each word to uppercase
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
6. map() with Tuples
Applies a function to each element of a tuple just like lists.
map() works with any iterable, including tuples.
7. map() vs for loop (why map() is better)
map() provides a shorter and cleaner alternative to loops for transforming iterables.
Using a loop:
Using map():
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges