Reputation: 8219
How do I convert all strings in a list to integers?
['1', '2', '3'] ⟶ [1, 2, 3]
Upvotes: 820
Views: 1691295
Reputation: 34655
Given:
xs = ['1', '2', '3']
Use map
then list
to obtain a list of integers:
list(map(int, xs))
In Python 2, list
was unnecessary since map
returned a list:
map(int, xs)
Upvotes: 1516
Reputation: 23071
int()
raises an error if an invalid value is fed. If you want to set these invalid values to NaN and convert the valid values in the list (similar to how pandas' to_numeric
behaves), you can do so using the following list comprehension:
[int(x) if x.replace('-','', 1).replace('+','',1).isdecimal() else float('nan') for x in lst]
It is essentially checking if a value is decimal or not (either negative or positive). Scientific notation (e.g. 1e3
) can also be a valid integer, in that case, we can add another condition to the comprehension (albeit less legible):
[int(x) if x.replace('-','', 1).replace('+','',1).isdecimal() else int(e[0])*10**int(e[1]) if (e:=x.split('e',1))[1:] and e[1].isdecimal() else float('nan') for x in lst]
For lst = ['+1', '2', '-3', 'string', '4e3']
, the above comprehension returns [1, 2, -3, nan, 4000]
. With minor adjustments, we can make it handle floats too but that's a separate topic.
map()
is about 64% faster than the list comprehension. As can be seen from the following performance plot, map()
outperforms list comprehension regardless of list size.
The code used to produce the plot:
from random import choices, randint
from string import digits
from perfplot import plot
plot(
setup=lambda n: [''.join(choices(digits, k=randint(1,10))) for _ in range(n)],
kernels=[lambda lst: [int(x) for x in lst], lambda lst: list(map(int, lst))],
labels= ["[int(x) for x in lst]", "list(map(int, lst))"],
n_range=[2**k for k in range(4, 22)],
xlabel='Number of items',
title='Converting strings to integers',
equality_check=lambda x,y: x==y);
Upvotes: 1
Reputation: 8772
Use a list comprehension on the list xs
:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]
Upvotes: 485
Reputation: 825
There are several methods to convert string numbers in a list to integers.
In Python 2.x you can use the map function:
>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]
Here, It returns the list of elements after applying the function.
In Python 3.x you can use the same map
>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]
Unlike python 2.x, Here map function will return map object i.e. iterator
which will yield the result(values) one by one that's the reason further we need to add a function named as list
which will be applied to all the iterable items.
Refer to the image below for the return value of the map
function and it's type in the case of python 3.x
The third method which is common for both python 2.x and python 3.x i.e List Comprehensions
>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
Upvotes: 13
Reputation: 51643
If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.
So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
Output:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
To also handle iterables inside iterables you can use this helper:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
Output:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
Upvotes: 8
Reputation: 3177
The answers below, even the most popular ones, do not work for all situations. I have such a solution for super resistant thrust str. I had such a thing:
AA = ['0', '0.5', '0.5', '0.1', '0.1', '0.1', '0.1']
AA = pd.DataFrame(AA, dtype=np.float64)
AA = AA.values.flatten()
AA = list(AA.flatten())
AA
[0.0, 0.5, 0.5, 0.1, 0.1, 0.1, 0.1]
You can laugh, but it works.
Upvotes: 0
Reputation: 183
You can easily convert string list items into int items using loop shorthand in python
Say you have a string result = ['1','2','3']
Just do,
result = [int(item) for item in result]
print(result)
It'll give you output like
[1,2,3]
Upvotes: 8
Reputation: 518
I also want to add Python | Converting all strings in list to integers
Method #1 : Naive Method
# Python3 code to demonstrate
# converting list of strings to int
# using naive method
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using naive method to
# perform conversion
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Method #2 : Using list comprehension
# Python3 code to demonstrate
# converting list of strings to int
# using list comprehension
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using list comprehension to
# perform conversion
test_list = [int(i) for i in test_list]
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Method #3 : Using map()
# Python3 code to demonstrate
# converting list of strings to int
# using map()
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using map() to
# perform conversion
test_list = list(map(int, test_list))
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Upvotes: 0
Reputation: 84
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("")
.
Upvotes: 3
Reputation: 708
Here is a simple solution with explanation for your query.
a=['1','2','3','4','5'] #The integer represented as a string in this list
b=[] #Fresh list
for i in a: #Declaring variable (i) as an item in the list (a).
b.append(int(i)) #Look below for explanation
print(b)
Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).
Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.
Output console:
[1, 2, 3, 4, 5]
So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.
Upvotes: 2
Reputation: 367
A little bit more expanded than list comprehension but likewise useful:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return(str_list)
e.g.
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
Also:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
Upvotes: 5