Reputation: 21
hi
how to convert a = ['1', '2', '3', '4']
into a = [1, 2, 3, 4] in one line in python ?
Upvotes: 1
Views: 3747
Reputation: 1886
l = []
a = ['1', '2', '3', '4']
l = [(int(x)) for x in a]
print l
[1, 2, 3, 4]
Upvotes: 0
Reputation: 83032
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']
Upvotes: 1
Reputation: 994649
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.
Upvotes: 8
Reputation: 799450
With a list comprehension.
a[:] = [int(x) for x in a]
Upvotes: 8