Python’s Map() Function: Iterate without Looping

HALL of Tech
By -
0
Python’s Map() Function: Iterate without Looping https://ift.tt/3Svug4O

Python map() is an important function when working with Python iterables (tuples, lists, etc.). Essentially, what this function does is allow you to process and transform items that can be iterated upon, meaning it can be repeated without having to use a loop.

Think of the map() function this way: it’s used to apply a function to each item within an iterable and returns the results as a list. The map() function accepts two parameters: the function that is to be applied and the iterable for which it is to be applied.

Hold up.

Before we go any further, let’s define an iterable.

An iterable is an object that can be looped through (or iterated). Lists, tuples, sets, dictionaries, and strings are all iterables.

Consider the following:

Open the Python interpreter with the command:

python3


Issue the following:

list("My name is Jack Wallen)


What we’ve done is create a list that is composed of a string of characters. The output of that list() function would look like this:

['M', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'J', 'a', 'c', 'k', ' ', 'W', 'a', 'l', 'l', 'e', 'n']


What it did was iterate through each character of the list.

Another example uses the sum() function like so:

sum([5, 10, 15])


The function would iterate through all three numbers and output the total, which is 30.

There are several built-in functions that accept iterables as arguments, such as list, tuple, dict, set, sum, sorted, any, all, max, and min.

And that’s iterables in a nutshell.

But how do we use iterables with the map() function? First, let’s examine the basic syntax. As I mentioned, the map() function accepts two parameters, which are:

  • function – a function that instructs map to pass each element of a given iterable.
  • iterable – the iterable that is to be mapped.

The syntax looks like this:

map(function, iterable)


In other words:

map(function, iterable[iterable1, iterable2, iterable3, … ])


Let me show you how this works.

A Basic map() Function

Let’s create a simple Python program that will square a list of numbers (an iterable). We’ll define our first function like so:

def square(n):
     return n ** 2


Now that we’ve defined our function, we need to define the variables, by way of an iterable. For this, we’ll use a list and define it as numbers like so:

numbers = [2, 4, 6, 8, 10]


Next, we’ll define results using map(). Our function will be square (from our defined function) and our iterable will be numbers (from our variable definition above). This line looks like:

result = map(square, numbers)


Finally, we’ll use the print() function in conjunction with the list() function to print results like so:

print(list(result))


The entire block of code looks like this:

def square(n):
   return n ** 2

numbers = [2, 4, 6, 8, 10]
result = map(square, numbers)
print(list(result))


Save and close the file (naming it something like map.py). Run this little Python application like so:

python3 map.py

The results will be:

[4, 16, 36, 64, 100]

Thanks to map(), it iterated through our numbers list, to create the square of each number.

If we were to use a loop for this same application, it would look something like this:

numbers = [2, 4, 6, 8, 10]
squared = []

for num in numbers:
   squared.append(num ** 2)

print(squared)


When you compare the code, they look equally as simple and consume roughly the same amount of space. What’s the difference? The map() function is far more efficient than a loop. As well, the map() function gives you items on demand, whereas the loop has to store values in memory. Imagine you have a massive amount of iterables. If you use a loop in that case, you’ll be storing a large amount of data in memory, whereas with the map() function, you don’t have to worry about that.

So, you get the same functionality with map(), without the high cost of overhead when using a loop. That’ll be crucial as your Python apps become larger and more complex.

Let’s make this a bit more complex. Say, for example, you have the following two lists:

numbers1 = [2, 4, 6, 8, 10]
numberrs2 = [12, 14, 16, 18, 20]


What if you wanted to add the top number to the bottom number of those two lists together? You can use a lambda function (which I’ll introduce in another article) by defining results as such:

result = map(lambda x, y: x + y, numbers1, numbers2)


Finally, we print our results with the following line:

print(list(result))


The entire code looks like this:

numbers1 = [2, 4, 6, 8, 10]
numbers2 = [12, 14, 16, 18, 20]

result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))


Save the file as map2.py and run it with the command:

python map2.py


The results would be:

[14, 18, 22, 26, 30]

The map() function iterated through each number in numbers1 and numbers2 adding the numbers in the first position in each, and then iterating through the rest of the lists.

And that’s how you use the Python map() function. When you need better control of your resources and have to work with large iterables, you should consider this over a loop every time.

The post Python’s Map() Function: Iterate without Looping appeared first on The New Stack.

Tags:

Post a Comment

0Comments

Post a Comment (0)