0

I am trying to use a very simple function like converting list of strings to int value. As per the description we should get the list as output.

I am very new to Python so not sure whether I am doing any mistake.

l1 = ['1', '2', '9', '7', '5', '3']
l1 = map(int, l1)
print(l1)

Output:

<map object at 0x00000209FD5DC248>
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

1

Map function returns an iterable object and NOT a list. What that means is that you can iterate through the output of map and access each individual element. This example code might make it more clear.

l1 = ['1', '2', '9', '7', '5', '3']  
l1 = map(int, l1)  
for i in l1:  
    print (i)  

The output for this is:
1
2
9
7
5
3

Now assuming that your want to get back a list, all you need to do is type cast the iterable object returned by map to a list by explicitly calling 'list'.

l1 = ['1', '2', '9', '7', '5', '3']  
l1 = list(map(int, l1))  
print(l1)  

which would give you something like this

[1, 2, 9, 7, 5, 3]
hypnos
  • 76
  • 3
  • The reason it's done this way is so that if you use `map` with something like a file, it'll work through it line by line rather than loading the whole thing into memory. This is useful if the file is too big to fit, or if you only plan to use the first few lines of it in any case and it's a waste to load the whole thing. – Jiří Baum Aug 30 '20 at 01:30
0

Major code:

numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result))

Complete Result:

# Return double of n 
def addition(n): 
return n + n 

# We double all numbers using map() 
numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result))

Output:

enter image description here

Academic
  • 281
  • 3
  • 12
0

In python 3.x in-built functions like map() return an iterable which can be 'iterated' upon using a simple for loop. For printing your answer as a list you need to wrap your function in a list() call or use a list comprehension.

>>>list(map(int, l1))
>>>[element for element in map(int, l1)]