Borislav Hadzhiev
Thu Jun 16 2022·2 min read
Photo by Sandra Seitamaa
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.
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 on each item of the iterable.
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.
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.
result = [*(1, 2), *(3, 4), *(5, 6)] print(result) # 👉️ [1, 2, 3, 4, 5, 6]
map()
function takes a function and an iterable as arguments and calls the function on each item of the iterable.An alternative approach would be to directly use a list comprehension.
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 like we did with the map()
function.