How to Map a List in Python

To map the list elements in Python, you can use the map() function. The map() function applies a function to each list element, returns an iterable map object, and calls the next() method to traverse the list.

Example 1

data = [19, 21, 46, 29, 11]

def square_of_numbers(num):
  return num * num


mappedList = map(square_of_numbers, data)

print(next(mappedList))
print(next(mappedList))
print(next(mappedList))

Output

361
441
2116

We can see that we defined a function called square_of_numbers(), which returns the numbers’ squares. We pass this function to the map() function, which returns the map object.

Example 2

To access each element of the map object, use the next() method. For example, we can create a list of the map object using the list() method.

data = [19, 21, 46, 29, 11]


def square_of_numbers(num):
  return num * num


mappedList = map(square_of_numbers, data)

print(list(mappedList))

Output

[361, 441, 2116, 841, 121]

Python map list with a lambda function

To use map() and lambda function with Python list, you can pass the lambda function in the map() function, which will return the map object. Python anonymous or lambda function is the function that is defined without a name.

data = [19, 21, 46, 29, 11]

mappedList = map(lambda num: num * num, data)

print(list(mappedList))

Output

[361, 441, 2116, 841, 121]

We don’t need to define a function in this example because lambda will do the job.

Listify the list of strings

We can listify the list of strings using the list() and map() methods.

data = ['grogu', 'dinjarin', 'ahsokatano']

mappedList = list(map(list, data))

print(list(mappedList))

Output

[['g', 'r', 'o', 'g', 'u'], ['d', 'i', 'n', 'd', ' ', 'j', 'a', 'r', 'i', 'n'], 
['a', 'h', 's', 'o', 'k', 'a', ' ', 't', 'a', 'n', 'o']]

That’s it.

1 thought on “How to Map a List in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.