Convert a Map object to a List in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Convert a Map object to a List in Python #

Use the list() class to convert a map object to a list, e.g. new_list = list(map(my_fuc, my_list)). The list class takes an iterable (such as a map object) as an argument and returns a list object.

main.py
my_list = ['1.1', '2.2', '3.3'] new_list = list(map(float, my_list)) print(new_list) # 👉️ [1.1, 2.2, 3.3] print(type(new_list)) # 👉️ <class 'list'>

We passed a map object to the list() class to convert it to a list.

The list class takes an iterable and returns a list object.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map() function in the example converts each item from the original list to a float.

You can also use the * iterable unpacking operator to convert a map object to a list.

main.py
my_list = ['1.1', '2.2', '3.3'] new_list = [*map(float, my_list)] print(new_list) # 👉️ [1.1, 2.2, 3.3] print(type(new_list)) # 👉️ <class 'list'>

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

main.py
result = [*(1, 2), *(3, 4), *(5, 6)] print(result) # 👉️ [1, 2, 3, 4, 5, 6]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

An alternative approach would be to directly use a list comprehension.

main.py
my_list = ['1.1', '2.2', '3.3'] new_list = [float(i) for i in my_list] print(new_list) # 👉️ [1.1, 2.2, 3.3]

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

In the example, we explicitly pass each list item to the float() class instead of doing it implicitly as we did with the map() function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.