Mastering the Python Map Function [+Video]

With Python’s map() function, you can apply a specific function to each element of an iterable.

It takes two arguments:

  • Function: Often it’s a lambda function that you can define on the fly. This is the function which you are going to apply on each element of an…
  • Iterable: This is the iterable which you convert into a new iterable where each element is the result of the applied map() function.

The result is a map() object.

What’s a Python map() object?

It’s just an iterator that saves all mapped elements so that you can iterate over them. Especially for large iterables this is much more efficient than a standard Python list.

A Simple Example

Consider the following simple example:

lst = [1, 2, 3]
f = lambda x: x + 1
# [2, 3, 4]

We create a list lst with three elements. Then, we create a function f that takes one argument (an integer in our case) and increments it by one. The map function simply applies the function f to each element in the list.

A Practical Puzzle Example to Test What You’ve Learned

def encrypt(s1):
s2 = map(lambda c : chr(ord(c) + 2), s1)
return ''.join(s2)

def decrypt(s1):
s2 = map(lambda c : chr(ord(c) - 2), s1)
return ''.join(s2)

s = "xtherussiansarecomingx"

You already know that computers only operate on 0s and 1s. Every single character in a string is encoded as a sequence of 0s and 1s. Unicode is one such encoding that maps a bunch of zeros and ones (a binary ordinal value) to a symbol that you can read (a character). The Unicode table assigns one binary or decimal value to each character. For example, the Unicode value 41 encodes the value ‘A’ and the Unicode value 42 the value ‘B’.

With Unicode, we create our own secret language via encryption and decryption functions. The functions encrypt and decrypt operate on a string literal s1. To encrypt or decrypt a string, we shift each character by two Unicode positions. The encrypt function shifts the string to the right, the decrypt function shifts it to the left.

We use the map function to implement this shift for each character in the string s1. Using the built-in function ord(), shifting a character is as simple as adding a bias value to the Unicode value of the respective character.

The result of both encryption and decryption is a sequence type. Hence, we join the sequence with the empty string as a separator to receive the final encrypted or decrypted string.

By calling the function encrypt() twice, the string is simply shifted by 2+2=4 positions in the Unicode table. Hence, the result of a double encryption plus a single decryption is the same as a single decryption, i.e., 2+2-2=2.

Therefore, the result is “True”.

Are you a master coder?
Test your skills now!

Leave a Comment

Your email address will not be published. Required fields are marked *