Why use the map() function?

The map() in Python is a built-in function. For each item of the iterable (e.g. list, tuple, etc.), the map() calls the defined function and returns a list of results. The first argument in the map() is that you need to pass a function without calling it. This means that there are no parentheses. The operation performed by map() is usually known as a mapping, as it maps every item in an iterable input to an iterable new item. This is achieved by applying map() to all things in the input iterable. Python uses the map concept from functional programming. The map operation considers the mapping function and the data vector as arguments and returns the new vector, which results in the development of the mapping function on each vector object. Syntax: The syntax of map() in python is: map(function, iterable) Let’s assume that you want to use a list of operations or functions to construct a new list for each variable and use those outputs. An example would be to have a list of numbers and to create a new list with their cubes. One way to do this is by going through the list of numbers you are using for loop, and using a function that returns the cube of each number or part. Following is a simple program using the map function in python that returns the cube of a number: # defining a function that returns the cube of a number  def cube(number):    return number**3  # original list  number_list = [1,2,3,4,5,6]  # list that will contain the squared numbers  number_list_cube = []  # using a for loop to iterate over our number_list and create a new list with the cubic values  for number in number_list:    number_list_cube.append(cube(number))  print(number_list_cube)   # output [1,4,9,16,25,36We have a list of numbers, number_list, and we want to create a new list, number_list_cube, that contains the squares of number_list. We use a for loop to loop over number_list, and append the square of each number or number to our number_list_cube list. The built-in python function called map is another way to do this. There are two arguments in the map function: the function we want to apply and the object or sequence to which we want to apply it (such as a list in this case). In other words, the map function maps or applies it to each element in the sequence. Working of map() function in Python: Two inputs as a function and an iterable object used by the map(). The function given to map() is a normal function and is iterated over all the values in the given object. For example, making a list of numbers, and finding the cube for each number. The function is required that will return the double of the number. The function will be as follows: def double(number):  return number+number Now we will create the list of items: number_list = [1,2,3,4,5] Now we will use the map() function to find the double of each item in the number-list.  def double(number):      return number*2  number_list = [1,2,3,4,5]  number_list = map(double, number_list)  print(list(number_list)) Output: [2, 4, 6, 8, 10] We have used list() in the code to iterate the output from the map. The map() function helps to get the double of each number. map() in Python with built-in functions: The map() in Python is a built-in function and can also be used with other built-in functions available in Python. In the example, we are going to make use of the Python pow() built-in function. It is given to map two list objects, one for each base and index parameter. The result is a list containing the power of each number in bases raised to the corresponding number in the index. Example: We have two lists, one is base and another is index. base= [10, 20, 30, 40, 50]  index= [1, 2, 3, 4, 5]  We will use pow() as the function to map().  base=[10, 20, 30, 40, 50]  index=[1, 2, 3, 4, 5]  powers=list(map(pow, base, index))  print(list(powers)) Output: [10, 400, 27000, 2560000, 312500000] map() in Python with Tuple: Tuples in Python are an ordered collection of objects. They are defined by enclosing the elements in parentheses (()). In certain instances, the tuple is identical to the list in terms of indexing, nested objects and repetition, but the tuple is immutable, unlike the lists. Even though tuples are defined using brackets, you still use square brackets to index and slice tuples, just like strings and lists. Example: In the following example we will use the function that will convert the values of the tuple into uppercase. def upperFunc(values):      return values.upper()  values_tuple = ('swift','java','python','go','kotlin')  new_list = map(upperFunc, values_tuple)  print(list(new_list)) Output: ['SWIFT', 'JAVA', 'PYTHON', 'GO', 'KOTLIN'] map() in Python with Dictionary: Dictionaries are the implementation by Python that is more generally known as an associative array. A dictionary is a collection of key-value pairs. It is defined by curly brackets({}). Dictionaries are both mutable and dynamic. They can be updated and deleted as needed. Dictionaries differ from lists as Dictionary elements are accessed via keys while List elements are accessed by their position in the list, via indexing. The dictionary is an iterator, you can use it inside the map() function. Example: def dictFunc(values):      return values*10  values_dict = {1,2,3,4,5}  finalitems = map(dictFunc, values_dict)  print(list(finalitems)) Output: [10, 20, 30, 40, 50] map() in Python with Set: Sets in Python are unordered and the elements of a set are unique i.e. they cannot be the same. You can modify a set, but the elements in the set must be immutable. Like dictionary set() is also an iterator, you can use it inside the map() function. Example: def setFunc(values):      return values*10  values_set = {1,2,3,4,5}  finalitems = map(setFunc, values_set)  print(list(finalitems)) Output: [10, 20, 30, 40, 50] map() in Python with Lambda function: A Lambda Function is an anonymous function that means a function without a name. A Lambda function contains multiple arguments with one expression. We use the def keyword to define a normal function in Python. Similarly, we use the lambda keyword to define an anonymous function in Python. Lambda functions are syntactically restricted to a single expression. We can use the lambda function inside the map() function in Python. Example: numbers = (1,2,3,4,5)  result = map(lambda x: x+x, numbers)  print(list(result)) Output: [2, 4, 6, 8, 10] map() in Python with Other Functional Tools: We can perform more complex transformations on iterables by using map() together with functional tools like filter() and reduce(). map() and filter(): In some problems we need to process an input iterable and return another iterable by filtering unnecessary values in an iterable input. The filter() of Python is a good choice in this situation. Filter() returns the iterable input items for which the function returns true. If no function is passed, filter() uses the identity function. This implies filter() monitors each item in iterable for its true value and filters all falsy items out. Example: If we want to calculate the square root of all the values in a list and if our list have negative values, we’ll get an error because the square root isn’t defined for negative numbers. In order to prevent this problem, filter() is used to filter out all negative values and then find the square root of the remaining positive values. 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]) map() and reduce(): Another function that exists in functool module of Python is reduce() in the standard library of Python. Reduce() is another key functional method in Python that is helpful when an iterable feature needs to be added to and reduced to a single cumulative value. This form of action is generally called reducing or folding. Example: We will use map() and reduce() to calculate the total size of all the files that live in your home directory. import functools  import operator  import os  import os.path  files = os.listdir(os.path.expanduser(“~”))  functools.reduce(operator.add, map(os.path.getsize, files)) We will call os.path.expanduser("~") to get the path to your home directory. Then you call os.listdir() on that path to get a list with the paths of all the files that live there. The call to map() uses os.path.getsize() to get the size of each file. You eventually use reduce() to obtain the total sum of the size of each file using operator.add(). The end result is the total file size in bytes of your home directory. Generator Expressions instead of map() in Python: map() in python returns a map object, an iterator that returns items on request. The natural substitution for map() is therefore a generator expression. Generator expressions return generator objects, which are also iterators, which yield items on request. A tiny difference occurs between a list comprehension and a generator expression. The list uses a pair of square brackets ([]) while generator expressions use a pair of parentheses (()). If you want to turn a list comprehension into a generator expression, you just need to replace the square brackets with parentheses. def square(number):  return number ** 2  numbers = [1, 2, 3, 4, 5]  gen_exp = (square(x) for x in numbers)  print(list(gen_exp)) Output: [1, 4, 9, 16, 25] Generator expressions are commonly used as arguments in function calls.  Conclusion:map() in python allows to perform operations on iterables. Map() usually helps you to convert and process iterables without directly using a loop. Python map() is a built-in-function that applies a function to all the input items of an iterator. For example, a list, tuple, etc. can be an iterator, and it returns a map object that can be iterated. The map() function will add all the items inside the iterator to the specified function, and then return an iterable map object, i.e. tuple, list, etc. map() in Python is an embedded function that can also be used in Python with other integrated functions.

Why use the map() function?

10K
• by Abhresh S
• 01st Feb, 2021
• Last updated on 12th Mar, 2021

Themap() in Python is a built-in function. For each item of the iterable (e.g. list, tuple, etc.), the map() calls the defined function and returns a list of results. The first argument in the map() is that you need to pass a function without calling it. This means that there are no parentheses.

The operation performed by map() is usually known as a mapping, as it maps every item in an iterable input to an iterable new item. This is achieved by applying map() to all things in the input iterable.

Python uses the map concept from functional programming. The map operation considers the mapping function and the data vector as arguments and returns the new vector, which results in the development of the mapping function on each vector object.

Syntax:

The syntax of map() in python is:

map(function, iterable)

Let’s assume that you want to use a list of operations or functions to construct a new list for each variable and use those outputs. An example would be to have a list of numbers and to create a new list with their cubes. One way to do this is by going through the list of numbers you are using for loop, and using a function that returns the cube of each number or part.

Following is a simple program using the map function in python that returns the cube of a number:

# defining a function that returns the cube of a number
def cube(number):
return number**3
# original list
number_list = [1,2,3,4,5,6]
# list that will contain the squared numbers
number_list_cube = []
# using a for loop to iterate over our number_list and create a new list with the cubic values
for number in number_list:
number_list_cube.append(cube(number))
print(number_list_cube)
#

output

 [1,4,9,16,25,36

We have a list of numbers,number_list, and we want to create a new list,number_list_cube, that contains the squares ofnumber_list. We use a for loop to loop overnumber_list, and append the square of each number ornumberto ournumber_list_cubelist.

The built-in python function called map is another way to do this. There are two arguments in the map function: the function we want to apply and the object or sequence to which we want to apply it (such as a list in this case). In other words, the map function maps or applies it to each element in the sequence.

Working of map() function in Python:

Two inputs as a function and an iterable object used by the map(). The function given to map() is a normal function and is iterated over all the values in the given object.

For example, making a list of numbers, and finding the cube for each number.

The function is required that will return the double of the number. The function will be as follows:

def double(number):
return number+number 

Now we will create the list of items:

number_list = [1,2,3,4,5]

Now we will use the map() function to find the double of each item in the number-list.

def double(number):
return number*2
number_list = [1,2,3,4,5]
number_list = map(double, number_list)
print(list(number_list)) 

Output:

[2, 4, 6, 8, 10]

We have used list() in the code to iterate the output from the map. The map() function helps to get the double of each number.

map() in Python with built-in functions:

The map() in Python is a built-in function and can also be used with other built-in functions available in Python. In the example, we are going to make use of the Python pow() built-in function. It is given to map two list objects, one for each base and index parameter. The result is a list containing the power of each number in bases raised to the corresponding number in the index.

Example:

We have two lists, one is base and another is index.

base= [10, 20, 30, 40, 50]
index= [1, 2, 3, 4, 5]
We will use pow() as the function to map().
base=[10, 20, 30, 40, 50]
index=[1, 2, 3, 4, 5]
powers=list(map(pow, base, index))
print(list(powers)) 

Output:

[10, 400, 27000, 2560000, 312500000]

map() in Python with Tuple:

Tuples in Python are an ordered collection of objects. They are defined by enclosing the elements in parentheses (()). In certain instances, the tuple is identical to the list in terms of indexing, nested objects and repetition, but the tuple is immutable, unlike the lists.

Even though tuples are defined using brackets, you still use square brackets to index and slice tuples, just like strings and lists.

Example:

In the following example we will use the function that will convert the values of the tuple into uppercase.

def upperFunc(values):
return values.upper()
values_tuple = ('swift','java','python','go','kotlin')
new_list = map(upperFunc, values_tuple)
print(list(new_list)) 

Output:

['SWIFT', 'JAVA', 'PYTHON', 'GO', 'KOTLIN']

map() in Python with Dictionary:

Dictionaries are the implementation by Python that is more generally known as an associative array. A dictionary is a collection of key-value pairs. It is defined by curly brackets({}).

Dictionaries are both mutable and dynamic. They can be updated and deleted as needed. Dictionaries differ from lists as Dictionary elements are accessed via keys while List elements are accessed by their position in the list, via indexing.

The dictionary is an iterator, you can use it inside the map() function.

Example:

def dictFunc(values):
return values*10
values_dict = {1,2,3,4,5}
finalitems = map(dictFunc, values_dict)
print(list(finalitems)) 

Output:

[10, 20, 30, 40, 50]

map() in Python with Set:

Sets in Python are unordered and the elements of set are unique i.e. they cannot be the same. You can modify a set, but the elements in the set must be immutable. Like dictionary set() is also an iterator, you can use it inside the map() function.

Example:

def setFunc(values):
return values*10
values_set = {1,2,3,4,5}
finalitems = map(setFunc, values_set)
print(list(finalitems)) 

Output:

[10, 20, 30, 40, 50]

map() in Python with Lambda function:

ALambda Functionis an anonymous function thatmeans a function without a name. A Lambda function contains multiple arguments with one expression.

We use thedefkeyword to define a normal function in Python. Similarly, we use thelambdakeyword to define an anonymous function in Python.Lambda functions are syntactically restricted to a single expression.

We can use the lambda function inside the map() function in Python.

Example:

numbers = (1,2,3,4,5)
result = map(lambda x: x+x, numbers)
print(list(result)) 

Output:

[2, 4, 6, 8, 10]

map() in Python with Other Functional Tools:

We can perform more complex transformations on iterables by using map() together with functional tools like filter() and reduce().

map() and filter():

In some problems we need to process an input iterable and return another iterable by filtering unnecessary values in an iterable input. The filter() of Python is a good choice in this situation.

Filter() returns the iterable input items for whichthe function returns true. If no function is passed, filter() uses the identity function. This implies filter() monitors each item in iterable for its true value and filters all falsy items out.

Example:

If we want to calculate the square root of all the values in a list and if our list have negative values, we’ll get an error because the square root isn’t defined for negative numbers. In order to prevent this problem, filter() is used to filter out all negative values and then find the square root of the remaining positive values.

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]) 

map() and reduce():

Another function that exists in functool module of Python is reduce() in the standard library of Python. Reduce() is another key functional method in Python that is helpful when an iterable feature needs to be added to and reduced to a single cumulative value. This form of action is generally called reducing or folding.

Example:

We will use map() and reduce() to calculate the total size of all the files that live in your home directory.

import functools
import operator
import os
import os.path
files = os.listdir(os.path.expanduser(“~”))
functools.reduce(operator.add, map(os.path.getsize, files)) 

We will callos.path.expanduser("~")to get the path to your home directory. Then you callos.listdir()on that path to get a list with the paths of all the files that live there. The call to map() uses os.path.getsize() to get the size of each file. You eventually use reduce() to obtain the total sum of the size of each file using operator.add(). The end result is the total file size in bytes of your home directory.

Generator Expressions instead of map() in Python:

map() in python returns a map object, an iterator that returns items on request. The natural substitution for map() is therefore a generator expression. Generator expressions return generator objects, which are also iterators, which yield items on request.

A tiny difference occurs between a list comprehension and a generator expression. The list uses a pair of square brackets ([]) while generator expressions use a pair of parentheses (()). If you want to turn a list comprehension into a generator expression, you just need to replace the square brackets with parentheses.

def square(number):
return number ** 2
numbers = [1, 2, 3, 4, 5]
gen_exp = (square(x) for x in numbers)
print(list(gen_exp)) 

Output:

[1, 4, 9, 16, 25]

Generator expressions are commonly used as arguments in function calls.

Conclusion:

map() in python allows to perform operations on iterables. Map() usually helps you to convert and process iterables without directly using a loop.

Python map() is a built-in-function that applies a function to all the input items of an iterator. For example, a list, tuple, etc. can be an iterator, and it returns a map object that can be iterated. The map() function will add all the items inside the iterator to the specified function, and then return an iterable map object, i.e. tuple, list, etc. map() in Python is an embedded function that can also be used in Python with other integrated functions.

Abhresh S

Freelance Corporate Trainer

An Online Technical Trainer by profession! And Content writer by hobby! Interested in sharing quality knowledge to make the Industry grow better towards better success and better tomorrow! With a Guru Mantra of - "Keep Learning & Keep Practicing".

9 Stupendous Technologies You Might Be Using In Near Future

307
9 Stupendous Technologies You Might Be Using In Ne...

Our lives have made a 360 degree turn in the past ... Read More

Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable language” and it means that Scala grows with you. In recent times, Scala has attracted developers because it has enabled them to deliver things faster with fewer codes. Developers are now much more interested in having Scala training to excel in the big data field. The Scala community has grown over the years and it has now become a standard for enterprise, start-ups and universities alike. Scala is now being used by many companies and individuals to build their own new ideas. Play Framework, Akka, Apache Spark, etc are some of the tools and projects created using Scala. Scala is now the next wave of computation engines and more importance has been given to the speed processing rather than the size of the batch, and the ability to process event streaming in real-time. 1.Apache Spark Apache Spark can be considered as the replacement of MapReduce. In late 2013, Cloudera, the largest Hadoop vendor supported the idea of replacing MapReduce with Apache Spark. Spark is developed by AMPLab and it is a fast and general purpose engine for large-scale data processing. Spark effectively provides an alternative for Hadoop’s two stage MapReduce model. It has improved the performance of certain applications to 100 times with its fine grain operators, in-memory caching of intermediate data, and data flow optimization. 2. Scalding Scalding has been introduced and maintained by Twitter. It provides full benefits of Scala syntax and functional operations. Scala is a powerful language for solving functional problems. Scalding makes comprehensive use of Scala and it is an extension to cascading that enables application development with Scala. If we focus on the benefits of Scalding, data applications can be built with Scala. With simple and concise syntax code becomes easier to interpret. Scalding has filled the benefits of cascading application framework. 3. Apache Kafka Built and maintained by LinkedIn, Apache Kafka is a distributed streaming platform. Apache Kafka allows the user to publish and subscribe streams of data, just like a messaging system. Kafka is responsible for handling hundred of megabytes of read-write traffic per second from thousand of clients. It is also empowered by Scala and we can see the influence of the language. Real-time data pipelines and streaming apps can be built by using Apache Kafka. Yahoo Kafka Manager is also written in Scala and the web console is built using Play Framework. The Kafka Manager is being used by many teams including the Media Analytics team. It interacts with an actor-based, in-memory model built with Akka and Apache Curator. 4. Finagle Built by the people at twitter, Finagle can be considered as one of the best case using Scala. It is used to build high-concurrency servers and is an extensible RPC system for JVM. Finagle was intended to provide high performance, concurrency along with Scala and Java idiomatic APIs. Finagle is known for the optimal use of available system resources and high scalability through concurrency. It uses safe, simple and clean concurrent programming model which is based on Futures. All these results in safe and modular programs.
531
Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable languag... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access •$password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example:$first=$_POST[‘first’];$last=$_POST[‘last’];$phone=$_POST[‘phone’];$mobile=$_POST[‘mobile’];$fax=$_POST[‘fax’];$email=$_POST[’email’];$web=$_POST[‘web’]; …$query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”;$result=mysql_query(\$query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
3969
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More