Skip to main content

Usage of map() function in Python

Usage of map() function in Python - Explained

Python map() function is very helpful when we need to call a specific function for each element in an iterable and return the result as an iterable of type map object. 

In other words, map() function would call another function for each element in an iterable (range, list, tuple...) and returns an iterable.

Syntax

map(function, iterable1, iterable2,...)

map() accepts a minimum of two parameters.
  • A function (to be called)
  • An iterable (function to be executed for each element in an iterable)
And, can have multiple iterables as required by the function passed in the first parameter. If the function requires two parameters then two iterables to be passed in parameters for map function. 

Let's have a look at an example to calculate the square of each number in the range of 0 to 5.

Without using map()


map() function in Python

In the above example, 
  • Line - 3: Create empty list to hold square of numbers. 
  • Line - 6: for loop over range of 0 and 5. 
  • Line - 7: pass number to the function 'square' to get the square of the number and add it to the list created. 
  • Line - 13: Function 'square' to accept a number as parameter and return the square of the number as result. 
Here we are using for loop to call the function for each number in the range of 0 and 5. 

We can use map() function to do that instead of having for loop. 

With map() function


map() function in Python

In the above example, 
  • Line - 3: We are passing the function 'square' as first parameter and range(5) as second parameter to the map function and assigning the result to variable 'square_list'. 
Only difference here would be 'square_list' is an iterable of type map object not a list. Print statement above doesn't actually print squares instead it just prints '<map object at memory_location>'.

Values in the map object can either be accessed by using this in for loop or simply by converting the map object to list. 

square_list = list(map(square, range(5)))

Just like in the above example, if we are only creating the function to use it in map, we can avoid function creation by using lambda expression. 

map() with lambda expression


map() with lambda expression in Python

In the above example, 
  • Line - 3: We are using lambda expression to calculate the square of a number in the range 0 to 5 instead of having to create a function. 

map() with two or more iterables

We can pass multiple iterables to map function as required by the function passed. 

Let's have a look at an example with a function to add two numbers and return the result by passing two iterables. 

map function with multiple iterables

In the above example, 
  • Line - 14: Creating a function to accept two numbers and return the sum of two numbers.
  • Lines - 3 & 6: Creating two lists with numbers. Note that the number of elements in the two lists aren't same. 
  • Line - 9: passing the function and two lists to the map function. 
There are couple points to note regarding the way map function works when two or more iterables are passed. 
  • Elements in the same index position would be passed as parameters to the function. E.g.: Index 0 from first list & second list, Index 1 from first list & second list, Index 2 from first list & second list and so on.
  • If the number of elements in the lists aren't same, map function would return the results equal to the smallest index. In the above example second element has got only 3 elements and the result would contain the sum of first 3 elements from the two lists. 

map() function with Python BIF

Like user created functions, we can use Python Built-In Functions as well inside the map() function. 

We will have a look at converting the numbers in a string (or user input) to a list by converting them to int. 

map() with int in Python

In the above example, 
  • Line - 2: A string called 'numbers' with a string containing numbers. This can either be an user input (which is most common scenario) that is to be split into a list of numbers. 
  • Line - 5: We are passing function 'int' and an iterable (by splitting the string into a list using split method). 
Like any other function, int would convert each of the number from the iterable passed and returns the integer value. This is them stored as a map object and converted to list (by using list function). 


Hope the above info was useful in understanding the usage of map() function. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i