<code>map(function, iterable)</code>
Table of Contents
Table of Contents
Introduction
Python is a high-level programming language that is popular among developers for its simplicity and readability. One of the most commonly used functions in Python is the map function. In this article, we will explore what the map function is and how it can be used in Python programming.What is the Map Function?
The map function is a built-in function in Python that takes in two arguments: a function and an iterable object. It applies the function to every element in the iterable and returns a new iterable object with the modified values.How to Use the Map Function?
The syntax for the map function is as follows:map(function, iterable)
function
argument specifies the function to apply to each element in the iterable
. The iterable
argument can be any object that can be iterated over, such as a list, tuple, or string. Example 1: Using the Map Function to Square Elements in a List
Let's say we have a list of numbers and we want to square each element in the list. We can achieve this using the map function as follows:numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
lambda x: x**2
to each element in the list using the map function. The result is a new list of squared numbers, which is printed to the console. Example 2: Using the Map Function to Convert Temperatures from Celsius to Fahrenheit
Let's say we have a list of temperatures in Celsius and we want to convert them to Fahrenheit. We can achieve this using the map function as follows:celsius_temperatures = [0, 10, 20, 30, 40]
fahrenheit_temperatures = list(map(lambda x: (9/5)*x + 32, celsius_temperatures))
print(fahrenheit_temperatures)
lambda x: (9/5)*x + 32
to each element in the list using the map function. The result is a new list of temperatures in Fahrenheit, which is printed to the console. Example 3: Using the Map Function to Convert Strings to Integers
Let's say we have a list of strings that represent numbers and we want to convert them to integers. We can achieve this using the map function as follows:string_numbers = ['1', '2', '3', '4', '5']
int_numbers = list(map(int, string_numbers))
print(int_numbers)
int
to each element in the list using the map function. The result is a new list of integers, which is printed to the console.