1

hi
how to convert a = ['1', '2', '3', '4']
into a = [1, 2, 3, 4] in one line in python ?

samy
  • 21
  • 1
  • 4

4 Answers4

8

With a list comprehension.

a[:] = [int(x) for x in a]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    >>> a = [int(x) for x in a[:]] (I would do it like this, In words: make a list of int(x) for every x in a copy of a, make it the new a). I'm unable to see such an explanation to your way. Could you explain it, please? – ThisIsMeMoony Dec 30 '10 at 08:37
  • @ThisIsMeMoony: http://stackoverflow.com/questions/4081561/what-is-the-difference-between-list-and-list-in-python/4081587#4081587 – Ignacio Vazquez-Abrams Dec 30 '10 at 08:46
  • @ThisIsMeMoony: In addition to what Ignacio posted, your code is needlessly making a shallow copy (you can just iterate the old list without slicing). –  Dec 30 '10 at 09:04
8

You can use map():

a = map(int, a)

This is an alternative to the (more common) list comprehension, that can be more succinct in some cases.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

With a generator:

a[:] = (int(x) for x in a)

... list comprehensions are so ummmmm, 2.1, don't you know?

but please be wary of replacing the contents in situ; compare this:

>>> a = b = ['1', '2', '3', '4']
>>> a[:] = [int(x) for x in a]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]

with this:

>>> a = b = ['1', '2', '3', '4']
>>> a = [int(x) for x in a]
>>> a
[1, 2, 3, 4]
>>> b
['1', '2', '3', '4']
John Machin
  • 81,303
  • 11
  • 141
  • 189
  • 1
    Isn't it a bit presumptuous to assume that a generator can be used instead of a list in the original case? – pafcu Dec 30 '10 at 11:37
  • It works with a generator, but it's pointless because the implementation creates a temporary list internally, and if it didn't, the code would blow up because the list would be modified while reading it. Using a list instead of a generator would force people trying to understand your code to think how `a[:] = ...` works internally to be sure that it won't blow up. – Rosh Oxymoron Dec 30 '10 at 13:10
  • @pafcu - note the assignment is not to `a` but to `a[:]`, which will replace the contents of list `a` with the values returned by the generator. – PaulMcG Dec 30 '10 at 13:58
  • 1
    @Rosh Oxy: It was intended to be an ironical supplement to the pointless `[:]` in the `a[:] = [int(x) for x in a]` answer which is sillier than `a = [....]` which is not as terse as `a = map(int, a)`. I crave your pardon for causing you to think. – John Machin Dec 30 '10 at 19:36
0
l = []
a = ['1', '2', '3', '4']
l = [(int(x)) for x in a]
print l
[1, 2, 3, 4]
Haresh Shyara
  • 1,826
  • 10
  • 13