Using map()
Function in Python
The map()
function in Python is used to apply a function to all the items in an input list. Here are some examples to demonstrate its usage:
Basic Example
# Example function to square a number
def square(num):
return num ** 2
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Applying map() function
squared_numbers = map(square, numbers)
# Converting map object to list
squared_numbers_list = list(squared_numbers)
print(squared_numbers_list)
# Output: [1, 4, 9, 16, 25]
Using map()
with Lambda Functions
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Using lambda function to square the numbers
squared_numbers = map(lambda x: x ** 2, numbers)
# Converting map object to list
squared_numbers_list = list(squared_numbers)
print(squared_numbers_list)
# Output: [1, 4, 9, 16, 25]
Mapping Multiple Iterables
# Lists of numbers
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
# Using lambda function to add corresponding elements of two lists
sum_numbers = map(lambda x, y: x + y, numbers1, numbers2)
# Converting map object to list
sum_numbers_list = list(sum_numbers)
print(sum_numbers_list)
# Output: [5, 7, 9]
Using map()
to Convert Data Types
# List of strings
str_numbers = ['1', '2', '3', '4', '5']
# Using map() to convert strings to integers
int_numbers = map(int, str_numbers)
# Converting map object to list
int_numbers_list = list(int_numbers)
print(int_numbers_list)
# Output: [1, 2, 3, 4, 5]
These examples showcase the versatility of the map()
function in applying various operations to elements of a list or multiple lists.
Understanding map()
Function
The map()
function applies a specified function to each item of an iterable (like a list or a tuple) and returns a map object (an iterator).
Example 1: Applying a Function to Each Item in an Iterable
The first example demonstrates using map()
to apply a function that calculates the length of each string in a tuple.
# Define a function that returns the length of a string
def myfunc(n):
return len(n)
# Apply the function to each item in the tuple using map()
x = map(myfunc, ('apple', 'banana', 'cherry'))
# Convert the map object to a list and print it
print(list(x))
# Output: [5, 6, 6]
Example 2: Mapping Two Iterables
The second example demonstrates using map()
with a function that takes two arguments. Here, two tuples are passed to the map()
function.
# Define a function that adds two numbers (or concatenates two strings)
def myfunc(a, b):
return a + b
# Apply the function to each pair of items in the tuples using map()
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
# Convert the map object to a list and print it
print(list(x))
# Output: ['appleorange', 'bananalemon', 'cherrypineapple']
Detailed Explanation
- Function Definition:
- The function
myfunc
is defined to return the length of a string in the first example. - In the second example,
myfunc
is defined to add (concatenate) two strings.
- The function
- Using
map()
:map(myfunc, iterable)
appliesmyfunc
to each item in theiterable
.map(myfunc, iterable1, iterable2)
appliesmyfunc
to each pair of items fromiterable1
anditerable2
.
- Converting to List:
- The result from
map()
is a map object. To see the results, it is often converted to a list usinglist()
.
- The result from
These examples illustrate the power of map()
in Python for applying functions to iterable items efficiently.
More examples to further understand the usage of the map()
function in Python.
Example 3: Converting Strings to Uppercase
Suppose we have a list of strings and we want to convert each string to uppercase.
# Define a function that converts a string to uppercase
def to_uppercase(s):
return s.upper()
# List of strings
strings = ['apple', 'banana', 'cherry']
# Apply the function to each item in the list using map()
uppercase_strings = map(to_uppercase, strings)
# Convert the map object to a list and print it
print(list(uppercase_strings))
# Output: ['APPLE', 'BANANA', 'CHERRY']
Example 4: Squaring Numbers in a List
Let’s say we have a list of numbers and we want to square each number.
# Define a function that squares a number
def square(n):
return n * n
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Apply the function to each item in the list using map()
squared_numbers = map(square, numbers)
# Convert the map object to a list and print it
print(list(squared_numbers))
# Output: [1, 4, 9, 16, 25]
Example 5: Adding Two Lists Element-Wise
Suppose we have two lists of numbers and we want to add them element-wise.
# Define a function that adds two numbers
def add(a, b):
return a + b
# Two lists of numbers
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Apply the function to each pair of items in the lists using map()
summed_list = map(add, list1, list2)
# Convert the map object to a list and print it
print(list(summed_list))
# Output: [5, 7, 9]
Example 6: Converting Numbers to Strings
If we have a list of numbers and we want to convert each number to a string.
# List of numbers
numbers = [10, 20, 30, 40]
# Apply the str function to each item in the list using map()
string_numbers = map(str, numbers)
# Convert the map object to a list and print it
print(list(string_numbers))
# Output: ['10', '20', '30', '40']
Example 7: Using Lambda with map()
We can also use lambda functions with map()
for simple operations.
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Apply a lambda function to square each number using map()
squared_numbers = map(lambda x: x * x, numbers)
# Convert the map object to a list and print it
print(list(squared_numbers))
# Output: [1, 4, 9, 16, 25]
Example 8: Combining map()
with Other Functions
We can use map()
with other built-in functions like len
.
# List of words
words = ['hello', 'world', 'python']
# Apply the len function to each word in the list using map()
word_lengths = map(len, words)
# Convert the map object to a list and print it
print(list(word_lengths))
# Output: [5, 5, 6]
These examples demonstrate the versatility of the map()
function in applying various transformations to items in iterables.