Chih- Yu Lin

1573787743

Python Map() | How to use the map() function with different types of sequences

Python map() function applies another function on a given iterable (List/String/Dictionary, etc.) and returns map object. In simple words, it traverses the list, calls the function for each element, and returns the results.

Python map object is also iterable holding the list of each iteration. We can also convert it to List or Dictionary or other types using their constructor functions.

In this tutorial, you’ll learn how to use the map() function with different types of sequences. Also, you can refer to the examples that we’ve added to bring clarity.

Python Map() Function Explained

Python Map() Function

The map() function takes at least two parameters. The first argument is a user-defined function, and then one or more iterable types.

If you pass only one iterable, then map() calls the function for each of its elements and returns map object with results.

However, if you provide multiple iterables, then the function will be called with each of their elements as arguments. In this case, the map() call stops after finishing up the shortest iterable argument.

Its syntax is as follows:

# Python map() syntax
map(in_function, iterable1[, iterable2, iterable3, ...])

Map() Function Examples

We’ll now give several examples using map() so that you can clearly understand what does it do and how should you use it.

But before beginning, we need a user-defined function that we can pass as the first argument to map(). So, here it is:

# User-defined function to pass to map()
# function as the first argument
def getLength(iterable):
    return len(iterable)

It calculates the length of iterable and returns in a map object.

Below is a method to print the map object. We’ll use it in all our examples.

# Function to print the map output
def show_result(map_object):
    for item in map_object:
        print(item, end=' ')
    print('')  # for new line

Also, we’ll use one more generic function to print the iterable.


# Generic Function to print the iterator and its content
def print_Iter(iter_in):
    if isinstance(iter_in, str):
        print("The input iterable, '{}' is a String. Its length is {}.".format(iter_in, len(iter_in)))
    if isinstance(iter_in, (list, tuple, set)):
        print("The input iterable, {} is a {}. It has {} elements.".format(iter_in, type(iter_in).__name__, len(iter_in)))
        for item in iter_in:
            print("The {} contains '{}' and its length is {}.".format(type(iter_in).__name__, item, len(item)))
    if isinstance(iter_in, dict):
        print("The input iterable, {} is a {}. It has {} elements.".format(iter_in, type(iter_in).__name__, len(iter_in)))
        for key, value in iter_in.items():
            print("Dict key is '{}' and value is {}.".format(key, value))

Python Function

String As Iterable In Map() Function

The below code pass a String type iterable in the map() and prints the result.


"""
 Desc:
  Python map() function to apply on a String iterable
"""

# Considering String as our iterable parameter
iter_String = "Python"
print_Iter(iter_String)
    
# Calling map() function on a string
map_result =  map(getLength, iter_String)
print("Type of map_result is {}".format(type(map_result)))

# Printing map() output
print("Lengths are: ")
show_result(map_result)

Please note that you’ll need to add the definition of the print_Iter(), getLength(), and show_result() in the above example. After that, you can run it. The output is:

The input iterable, 'Python' is a String. Its length is 6.
Type of map_result is <class 'map'>
Lengths are: 
1 1 1 1 1 1

Python String

List As Iterable In Map() Function

The below code shows how to use a list with the map() function.

"""
 Desc:
  Python map() function to apply on a List iterable
"""

# Considering List as our iterable parameter
iter_List = ["Python", "CSharp", "Java"]
print_Iter(iter_List)

# Calling map() function on a list
map_result =  map(getLength, iter_List)
print("Type of map_result is {}".format(type(map_result)))

# Printing map() output
print("Lengths are: ")
show_result(map_result)

The output is as follows:

The input iterable, ['Python', 'CSharp', 'Java'] is a list. It has 3 elements.
The list contains 'Python' and its length is 6.
The list contains 'CSharp' and its length is 6.
The list contains 'Java' and its length is 4.
Type of map_result is <class 'map'>
Lengths are: 
6 6 4

Python List

Tuple As Iterable In Map() Function

In this example, we are using a tuple to pass in the map() function.

"""
 Desc:
  Python map() function to apply on a Tuple iterable
"""

# Considering Tuple as our iterable parameter
iter_Tuple = ("Python", "CSharp", "Java")
print_Iter(iter_Tuple)

# Calling map() function on a tuple
map_result =  map(getLength, iter_Tuple)
print("Type of map_result is {}".format(type(map_result)))

# Printing map() output
print("Lengths are: ")
show_result(map_result)

Running the above code brings the following output:


The input iterable, ('Python', 'CSharp', 'Java') is a tuple. It has 3 elements.
The tuple contains 'Python' and its length is 6.
The tuple contains 'CSharp' and its length is 6.
The tuple contains 'Java' and its length is 4.
Type of map_result is <class 'map'>
Lengths are: 
6 6 4

Python Tuple

Set As Iterable In Map() Function

Here, we are using a set type object to pass in the map() function and will see how it works.


"""
 Desc:
  Python map() function to apply on a Set iterable
"""

# Considering Set as our iterable parameter
iter_Set = {"Python", "CSharp", "Java"}
print_Iter(iter_Set)

# Calling map() function on a set
map_result =  map(getLength, iter_Set)
print("Type of map_result is {}".format(type(map_result)))

# Printing map() output
print("Lengths are: ")
show_result(map_result)

The result:


The input iterable, {'CSharp', 'Python', 'Java'} is a set. It has 3 elements.
The set contains 'CSharp' and its length is 6.
The set contains 'Python' and its length is 6.
The set contains 'Java' and its length is 4.
Type of map_result is <class 'map'>
Lengths are: 
6 6 4

Python Set

Dictionary As Iterable In Map() Function

Finally, we’ll apply the map() function to a dictionary type and see how it goes.

"""
 Desc:
  Python map() function to apply on a Dict iterable
"""

# Considering Dict as our iterable parameter
iter_Dict = {"Python":0, "CSharp":0, "Java":0}
print_Iter(iter_Dict)

# Calling map() function on a dictionary
map_result =  map(getLength, iter_Dict)
print("Type of map_result is {}".format(type(map_result)))

# Printing map() output
print("Lengths are: ")
show_result(map_result)

When you run the above example, it produces the result as:


The input iterable, {'Java': 0, 'CSharp': 0, 'Python': 0} is a dict. It has 3 elements.
Dict key is 'Java' and value is 0.
Dict key is 'CSharp' and value is 0.
Dict key is 'Python' and value is 0.
Type of map_result is <class 'map'>
Lengths are: 
4 6 6

The program prints the length of dictionary keys.

Python Dictionary

Convert Map Object To A Sequence

We’ve said earlier that you could use constructor functions to convert a map to list, tuple, set, etc. So, see this happening below.


"""
 Desc:
  Program to convert map object to list, tuple, and set
"""

# User-defined function to pass to map()
# function as the first argument
def getLength(iterable):
    return len(iterable)

# Function to print the map output
def show_result(iter_in):
    print("****************************")
    print("The input iterable, {} is a {}.".format(iter_in, type(iter_in).__name__))
    for item in iter_in:
        print("The {} contains '{}'.".format(type(iter_in).__name__, item))

# Converting map object to a list
map_result =  map(getLength, ["Python", "JavaScript", "Java"])
to_list = list(map_result)
show_result(to_list)

# Converting map object to a tuple
map_result =  map(getLength, ["Python", "JavaScript", "Java"])
to_tuple = tuple(map_result)
show_result(to_tuple)

# Converting map object to a set
map_result =  map(getLength, ["Python", "JavaScript", "Java"])
to_set = set(map_result)
show_result(to_set)

The above example produces the following result:


****************************
The input iterable, [6, 10, 4] is a list.
The list contains '6'.
The list contains '10'.
The list contains '4'.
****************************
The input iterable, (6, 10, 4) is a tuple.
The tuple contains '6'.
The tuple contains '10'.
The tuple contains '4'.
****************************
The input iterable, {10, 4, 6} is a set.
The set contains '10'.
The set contains '4'.
The set contains '6'.

Python Map() With The Anonymous Function

You’ve read our Python lambda tutorial which is also known as Anonymous function. In the map() call, we can send it as the first parameter.

This function is inline, and we can easily implement the length functionality using it. See the below example.


"""
 Desc:
  Python program to use lambda with map() function
"""

# Function to print the map output
def show_result(iter_in):
    print("****************************")
    print("The input iterable, {} is a {}.".format(iter_in, type(iter_in).__name__))
    for item in iter_in:
        print("The {} contains '{}'.".format(type(iter_in).__name__, item))

# Using lambda function with map()
map_result =  map(lambda item: len(item), ["Python", "JavaScript", "Java"])
to_list = list(map_result)
show_result(to_list)

The output is as follows:


****************************
The input iterable, [6, 10, 4] is a list.
The list contains '6'.
The list contains '10'.
The list contains '4'.

Map() Function With Multiple Iterables

In this example, we’ll demonstrate how to pass multiple iterables to map() function. Check the sample code below.

"""
 Desc:
  Python program to use lambda with map() function
"""

# Function to print the map output
def show_result(iter_in):
    print("****************************")
    print("The input iterable, {} is a {}.".format(iter_in, type(iter_in).__name__))
    for item in iter_in:
        print("The {} contains '{}'.".format(type(iter_in).__name__, item))

# Using lambda function with map()
map_result =  map(lambda arg1, arg2, arg3: [len(arg1), len(arg2), len(arg3)], ["Python", "JavaScript", "Java"], ("Go", "C", "C++", "Pascal"), {"Delphi", "VC++", "PHP", "MySQL", "MariaDB"})
to_list = list(map_result)
show_result(to_list)

The output:

****************************
The input iterable, [[6, 2, 6], [10, 1, 7], [4, 3, 4]] is a list.
The list contains '[6, 2, 6]'.
The list contains '[10, 1, 7]'.
The list contains '[4, 3, 4]'.

You can see the lambda function is taking three arguments as we are using three iterables. Also, the shortest of them is having three elements. Hence, it gets called three times.

We hope that after wrapping up this tutorial, you should feel comfortable in using the Python map() function. However, you may practice more with examples to gain confidence.

#python

What is GEEK

Buddha Community

Python Map() | How to use the map() function with different types of sequences
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Kennith  Blick

Kennith Blick

1625764320

How to use Functions in Python - Intermediate Python Tutorial #1

In this Python tutorial, we will learn the concept of functions in Python.
Knowing how to solve a problem dividing it into small tasks will make you a better programmer!
Python functions will help you on that. We will learn how to define a function, positional arguments, keyword arguments, default arguments and how to retrieve data from a function.

Playlist: Intermediate Python Tutorials - Video #1
Access the code here: https://github.com/rscorrea1/youtube.git

Timestamp:
00:00 - Summary of the video
00:26 - How to define a function
01:06 - Creating our first function
01:56 - Calling a function with no arguments
02:20 - Passing arguments to a function
02:34 - Argument definition
03:27 - Calling a function which expects one or more arguments
04:07 - Positional arguments
04:33 - Keyword arguments
06:57 - How to retrieve data from a function
10:35 - Default arguments
13:01 - Next video announcement

Thumbnail:
Photo by Mario Ho on Unsplash

#functions #python #intermediate python tutorial #how to use functions in python

Kennith  Blick

Kennith Blick

1625767860

How to use Functions in Python - Intermediate Python Tutorial #1

In this Python tutorial, we will learn the concept of functions in Python.
Knowing how to solve a problem dividing it into small tasks will make you a better programmer!
Python functions will help you on that. We will learn how to define a function, positional arguments, keyword arguments, default arguments and how to retrieve data from a function.

Playlist: Intermediate Python Tutorials - Video #1
Access the code here: https://github.com/rscorrea1/youtube.git

Timestamp:
00:00 - Summary of the video
00:26 - How to define a function
01:06 - Creating our first function
01:56 - Calling a function with no arguments
02:20 - Passing arguments to a function
02:34 - Argument definition
03:27 - Calling a function which expects one or more arguments
04:07 - Positional arguments
04:33 - Keyword arguments
06:57 - How to retrieve data from a function
10:35 - Default arguments
13:01 - Next video announcement

Thumbnail:
Photo by Mario Ho on Unsplash

#python #functions #intermediate python tutorial #how to use functions in python