Last updated: Apr 8, 2024
Reading timeยท3 min
Use the list()
class to convert a map object to a 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 with each item of the iterable.
map()
function in the example converts each item from the original list to a float.If you only need to iterate over the map
object, use a basic
for loop.
my_list = ['1.1', '2.2', '3.3'] map_obj = map(float, my_list) for item in map_obj: # 1.1 # 2.2 # 3.3 print(item)
The item
variable gets set to the current map
item on each iteration.
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 with 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]
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.
You can also use a for
loop to convert a map
object to a list.
my_list = ['1.1', '2.2', '3.3'] map_obj = map(float, my_list) new_list = [] for item in map_obj: new_list.append(item) print(new_list) # ๐๏ธ [1.1, 2.2, 3.3]
We declared a new variable and initialized it to an empty list and used a for
loop to iterate over the map
object.
On each iteration, we append the current item to the new list.
for
loop instead of the map
functionYou can also use a for
loop as a replacement for the map
function.
my_list = ['1.1', '2.2', '3.3'] new_list = [] for item in my_list: new_list.append(float(item)) print(new_list) # ๐๏ธ [1.1, 2.2, 3.3]
We used a for
loop to iterate over the list.
On each iteration, we convert the current item to a float and append the result to a new list.
As shown in the previous examples, the same can be achieved using a list
comprehension or the map()
function.
You can learn more about the related topics by checking out the following tutorials: