samy
samy

Reputation: 21

python list conversion

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

Upvotes: 1

Views: 3747

Answers (4)

Haresh Shyara
Haresh Shyara

Reputation: 1886

l = []
a = ['1', '2', '3', '4']
l = [(int(x)) for x in a]
print l
[1, 2, 3, 4]

Upvotes: 0

John Machin
John Machin

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

Greg Hewgill
Greg Hewgill

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799450

With a list comprehension.

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

Upvotes: 8

Related Questions