Question

I want to convert a str into an int in a list. Example:

x = ['1', '24', 'M', 'technician', '85711']

I want just the first element x[0] to switch to an int:

x = [1, '24', 'M', 'technician', '85711']
Was it helpful?

Solution

Just assign to an index of the list:

>>> x = ['1', '24', 'M', 'technician', '85711']
>>> x[0] = int(x[0])
>>> x
[1, '24', 'M', 'technician', '85711']
>>>

This solution keeps the list object the same too:

>>> x = ['1', '24', 'M', 'technician', '85711']
>>> id(x)
35174000
>>> x[0] = int(x[0])
>>> id(x)
35174000
>>>

OTHER TIPS

If you wish to convert just all digits to int in a mixed list , try it:

a = ['1', '24', 'M', 'technician', '85711']
b = map(lambda x: int(x) if str(x).isdigit() else x,a)
print b

output:

[1, 24, 'M', 'technician', 85711]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top