20

What is the easiest way to convert list with str into list with int in Python? For example, we have to convert ['1', '2', '3'] to [1, 2, 3]. Of course, we can use a for loop, but it's too easy.

vaultah
  • 40,483
  • 12
  • 109
  • 137
user285070
  • 735
  • 2
  • 11
  • 21

5 Answers5

24

Python 2.x:

map(int, ["1", "2", "3"])

Python 3.x (in 3.x, map returns an iterator, not a list as in 2.x):

list(map(int, ["1", "2", "3"]))

map documentation: 2.6, 3.1

codeape
  • 94,365
  • 23
  • 147
  • 176
  • 1
    I'm under the impression that `map` is generally disliked. It was even almost removed from Python 3. – pafcu Oct 10 '10 at 13:50
  • @pafcu I don't understand that. That sort of functionality is essential for functional programming... – Elliott Aug 15 '20 at 08:04
18
[int(i) for i in str_list]
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
5

You could also use list comprehensions:

new = [int(i) for i in old]

Or the map() builtin function:

new = map(int, old)

Or the itertools.imap() function, which will provide a speedup in some cases but in this case just spits out an iterator, which you will need to convert to a list (so it'll probably take the same amount of time):

import itertools as it
new = list(it.imap(int, old))
Chris Lutz
  • 70,285
  • 16
  • 125
  • 181
2

If your strings are not only numbers (ie. u''), you can use :

new = [int(i) for i in ["1", "2", "3"] if isinstance(i, int) or isinstance(i, (str, unicode)) and i.isnumeric()]
akarzim
  • 131
  • 5
1

If It is array and has installed numpy. We can used below code as well.

import numpy as np

np.array(['1', '2', '3'],dtype=int)
kgdc
  • 55
  • 1
  • 1
  • 10