Skip to main content
python map list

Python list map Example

This python tutorial help to understand python list map with example. Python provides map() method to apply a function to all the items of iterable and return map objects. This help to do some task on the all items of the list. You can pass one or more iterable to the map() function.

The map() method returned a map object and if we want to create an iterable (list, tuple etc.) out of it, then use the iterable method (list(), tuple() etc.) function. We can use the next() function to traverse the list.

You can also checkout other python list tutorials:

Python map() Example

Let’s create a function and apply it to items using map() method.

Syntax map() Method

map(fun, iter)

Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.).

Addition of number Using Python map()

Created an additional method that will add a self number.

def doubleNum(n):
  return n + n

numbers = (5, 6, 3, 4)
mappedList = map(doubleNum, numbers)
print(next(mappedList))
print(list(mappedList))

Output:

10
[10, 12, 6, 8]

We have defined the doubleNum() method, that ll returns the double number.We are passing this function to the map() function, which returns the map object.

Lambda with Python map()

The lambda is an anonymous function that is defined without a name. We can also use map() with lambda function and do some tasks on list items. We will create a square of the number using python lambda.

numbers = (5, 6, 3, 4)
mappedList = map(lambda x: x * x, numbers)
print(list(mappedList))

Output:

[25, 36, 9, 16]

in the above example, We haven’t defined the method to square of the list item numbers.

Listify the list of strings

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

names = ("parvez", "adam")
mappedList = list(map(list, names))
print(list(mappedList))

Output:

[['p', 'a', 'r', 'v', 'e', 'z'], ['a', 'd', 'a', 'm']]

Conclusion:

We have learned and understand the python map list example. You can also apply map function with other alterable like tuple, dictionaries etc. The lambda function also can be used with the map function.

Leave a Reply

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