Thứ Tư, Tháng Hai 12, 2025
spot_img
Homemap() function in Python - QuanTriMang.com

map() function in Python – QuanTriMang.com

Map in Python Used a lot in programming. So you know map function in Python Used for what? Let's find out with Quantrimang.com!

What is the map() function in Python?

Python is a powerful and flexible programming language that provides various built-in functions to implement a variety of data processing operations. One such function is the map() function, which is used to apply a feature to each element in an iteration (like a list or tuple) and return a new iteration with the same result.

map() takes two arguments: a function and an iterable. The function will be applied to each element of the iterable, and the repeating class is the iterable variable that the function will apply to. The syntax of the map() function is easy to remember.

Syntax of map() function in Python

map(function, iterable, ...)

Parameters of map() function

  • function: Function to execute for each element in the iterable.
  • iterable: a list, tuple, dictionary… want to browse.

You can pass multiple iterables to the map() function.

Return value from map()

The map() function browses all the elements of the iterable through the function and returns a list of results after execution.

The value returned from map() is called the map object. This object can be passed into the functions list() (to create a list in Python), or set() (to create a new set of elements)…

Example 1: How does map() work?

def binhphuong(n):
  return n*n

# viet boi Quantrimang.com
number = (25, 100, 225, 400)
ketqua = map(binhphuong, number)

# chuyen map object thanh list
print(list(ketqua))

When you run the program, the output will be:

[625, 10000, 50625, 160000]

In the above example, each element in the original tuple is squared up.

Example 2: How to use lambda function with map()

Because map() always requires parameters, lambda functions are often used with map().

In Python, a lambda or anonymous function is defined without a name. If normal functions are defined using the keyword defthen the anonymous function is defined using the keyword lambda.

Read more: Anonymous functions, Lambda in Python.

# viet boi Quantrimang.com
number = (5, 10, 15, 20)
result = map(lambda x: x*x, number)

# chuyen map object thanh list
sobinhphuong = list(result)
print(sobinhphuong)

Run the program, the returned results are:

[25, 100, 225, 400]

The result is no different example 1.

Example 3: Passing multiple iterator parameters to map() using lambda

In this example, the corresponding elements of the two lists are added.

num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))

The returned results are:

[9, 11, 13]

For example, use map() to convert the temperature from Celsius to Fahrenheit

Code:

# Mẫu chương trình Python cho hàm map()
temperatures = [0, 10, 20, 30, 40]
# Hàm lambda xác định công thức chuyển đổi
fahrenheit_temperatures = list(map( lambda x : (9/5)*x + 32, temperatures ))

# in danh sách nhiệt độ F
print(fahrenheit_temperatures)

Result:

[32.0, 50.0, 68.0, 86.0, 104.0]

Example 4: Use for loops

num = [3, 5, 7, 11, 13]
mul = []

for n in num:
    mul.append(n ** 2)
print (mul)

The returned results are:

Use for loops

Example 5: Using map() with len()

In this code, you have to use the Python function len() along with map() to find the length of some words.

example = ["Welcome", "to", "Simplilearn"]
x = list(map(len, example))
print(x)

The returned results are:

Using map() with len()

Example 6: Using map in Python with math.sqrt()

In the program below, you will first import the math library to use the math.sqrt() function with map in Python.

import math
num = [9, 36, 49, 81, 121]
x = list(map(math.sqrt, num))
print(x)

The returned results are:

Using map in Python with math.sqrt()

Using if statement with map() function

In this example, the double_even function doubles even numbers and leaves odd numbers intact. The map() function is used to apply this function to each element in a numbered list. An if statement is used in this function to implement the necessary conditional logic.

Time complexity analysis:

This map() function uses double_even for each element in the list. The time complexity of the map function is 0(n), where n is the number of elements in the list. The time complexity of the even argument multiplication function is constant, 0(1), because it only performs arithmetic and comparison operations. Therefore, the total time complexity of the program is O(n).

For example:

# Định nghĩa hàm nhân đôi số chẵn và để nguyên số lẻ
def double_even(num):
if num % 2 == 0:
return num * 2
else:
return num

# Tạo danh sách số để dùng hàm
numbers = [1, 2, 3, 4, 5]

# Dùng map để áp dụng hàm cho từng nguyên tố trong danh sách
result = list(map(double_even, numbers))

# In kết quả
print(result) # [1, 4, 3, 8, 5]

Result:

[1, 4, 3, 8, 5]

Map() and filter()

In some cases, you need to process an iterable input and return another repeatable value by filtering unnecessary values ​​in an iterable input. Python's Filter() is a good choice in this situation.

Filter() returns an iterable input item to the function that returns true. If no function is passed, filter() uses the identifier function. It says filter() monitors each iterable item for its correct value and filters out error items.

For example:

If you want to calculate the square root of all the values ​​in a list and if the list has negative values, you will receive an error message because square root is undefined for negative numbers. To avoid this problem, filter() is used to filter out all negative values, then find the square root of the remaining positive value.

import math 
def is_positive(num): 
return num >= 0 
def filtered_sqrt(numbers): 
filtered_iter = map(math.sqrt, filter(is_positive, numbers)) 
return list(filtered_iter) 
filtered_sqrt([100, 9, 225, -36, 0]) 

In this article, you learned about the map() function in Python. You've seen some examples to understand how this function works with various functions and iterables. Some key points to remember are that the map() function in Python is used to apply a conversion function to the entire iterable. Additionally, you can pass multiple iterables into a single map() function. If you want to learn more about iterables, maps, or other basic Python programming concepts, you can opt for Simplilearn's online Python Certification Course.

On the other hand, if you are interested in learning Data Science, you can opt for a Certificate Course in Data Science with Python. Both courses provide hands-on applied experience to help you excel in related fields.

See also: Built-in Python functions

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments