28

In the following i am trying to convert the first list to a integer list using the map function how can i achieve this

T1 = ['13', '17', '18', '21', '32']
print T1
T3=[map(int, x) for x in T1]
print T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]

Expected is:

T3=[13,17,18,21,32] 
Omer Mor
  • 5,216
  • 2
  • 34
  • 39
Rajeev
  • 44,985
  • 76
  • 186
  • 285

4 Answers4

63
>>> T1 = ['13', '17', '18', '21', '32']
>>> T3 = list(map(int, T1))
>>> T3
[13, 17, 18, 21, 32]

This does the same thing as:

>>> T3 = [int(x) for x in T1]
>>> T3
[13, 17, 18, 21, 32]

so what you are doing is

>>> T3 = [[int(letter) for letter in x] for x in T1]
>>> T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]

Hope that clears up the confusion.

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Your 2nd solution works fine but in the 1st one gives error, for it to work you need to do this: >>> T1 = ['13', '17', '18', '21', '32'] >>> T3 = map(int, T1) >>> T3=list(T3) or in short you can do this: >>> T1 = ['13', '17', '18', '21', '32'] >>> T3 = list(map(int, T1)) – Ghazali Feb 07 '20 at 07:15
  • 1
    @GhazaliShacklebolt Yes you are right because when I answered this it was in Python 2, i updated it like you said – jamylak Feb 08 '20 at 00:46
4
>>> T1 = ['13', '17', '18', '21', '32']
>>> print [int(x) for x in T1]
[13, 17, 18, 21, 32]

You don't need map inside your list comprehension. Map creates another list so you end up with a list of list.

Caveat: This will work if the strings are granted to be numbers otherwise it will raise exception.

Abhijit
  • 62,056
  • 18
  • 131
  • 204
3

You can do it like this

>>>T1 = ['13', '17', '18', '21', '32']
>>>list(map(int,T1))
progmatico
  • 4,714
  • 1
  • 16
  • 27
  • 1
    How is this any different from jamylak's [answer](https://stackoverflow.com/a/10145364/369450)? – Uyghur Lives Matter Feb 24 '18 at 18:30
  • 4
    I don't think this deserve a downvote, I just tried in Python3.6.0. Jamylak's answer gives result: `` but if you use list(map(int, T1)), it gives result [13, 17, 18, 21, 32] – Oscar Zhang Nov 06 '18 at 20:01
2

1.First,map function is map(func,iterable) 2.see this example:

T1=['13','17','18','21','32']
T3=[map(int, x) for x in T1]
print T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]

when choose x out,such as '13',is a sequence,so map(int,'13') return [1,3],so the iterable in map(func,iterable) is string.

3.see this example:

T1 = ['13', '17', '18', '21', '32']
>>>list(map(int,T1))

the iterable object in map function is list.so 'int' works on '13' as 13

xin wang
  • 31
  • 1