In Python, the map()
function is a built-in function that applies a given function to every item in an iterable (like a list, tuple, or dictionary).
Basic Syntax:
Python
map(function, iterable)
Use code with caution.
Parameters:
- function: The function to apply to each item in the iterable.
Python Classes in Mumbai
- iterable: The iterable (e.g., list, tuple, dictionary) whose elements will be passed to the function.
Return Value:
- A
map
object, which is an iterator that yields the results of applying the function to each item in the iterable.
Example:
Python
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
# Convert the map object to a list for printing
squared_numbers_list = list(squared_numbers)
print(squared_numbers_list) # Output: [1, 4, 9, 16, 25]
Use code with caution.
In this example:
- The
square
function is defined to calculate the square of a number.
- The
map()
function is used to apply the square
function to each element in the numbers
list.
- The resulting
map
object is converted to a list for printing.
Python Course in Mumbai
Key points to remember:
- The
map()
function returns an iterator, not a list. To get the results as a list, you need to convert the map
object using list()
.
- The
map()
function is often used for functional programming style, where you apply a function to a collection of elements.
- For simple operations, list comprehensions can be a more concise alternative to
map()
.
By understanding the map()
function, you can efficiently apply functions to elements in iterables and write more concise and functional Python code.