Table of Contents
Using map()
Method
Use the map()
method with list() method to convert string list to integer list in Python.
1 2 3 4 5 6 7 |
string_list = ['5', '6', '7', '8', '9'] integer_list = list(map(int, string_list)) print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 8 |
[5, 6, 7, 8, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
First, we defined a variable named string_list
and set its value to a list having five string values. Next, we used the map() method, which applied the int()
method to every element in string_list
to change its type from str
(string) to int
(integer). Once the map()
method applied int()
to all elements in string_list
, it returned a map object which we passed to the list()
method to convert it into a list and stored in the integer_list
variable.
Finally, we used the print()
method and passed integer_list
as a parameter to print it on the console. We also used a for
loop to iterate over the integer_list
to check each element’s data type in the integer_list
using the type()
function. We also printed the data type of each element on the console using the print()
method.
In the above example, the map()
method applied the int()
method, which was specified as a parameter. Note that we do not write parentheses (()
) while writing functions as a parameter in the map()
method. If you don’t want to use this approach because you are uncomfortable writing functions without ()
, then the following solution is for you.
1 2 3 4 5 6 7 |
string_list = ['5', '6', '7', '8', '9'] integer_list = list(map(lambda i: int(i), string_list)) print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 8 |
[5, 6, 7, 8, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
This example is similar to the previous one, but we used the lambda
expression (also called the lambda
function) this time; it is a small anonymous function which can accept any number of arguments but have one expression only. In the above example, the map()
method applied the lambda i: int(i)
function to every element in the string_list
to convert it from string to integer.
Unlike the previous example, once map()
applies the specified function to all elements in string_list
, it returns a map object that we passed to the list()
method to convert into a list and store it in integer_list
variable. Finally, we printed the entire list and data type of each element in integer_list
.
In Python 2, using the
list()
method to convert a map object to a list is not required because you would already have it, but you will not get any error if you use thelist()
method.
Using for
Loop
Use the for
loop to convert string list into integer list in Python.
1 2 3 4 5 6 7 8 |
string_list = ['5', '6', '7', '8', '9'] integer_list = [] for item in string_list: integer_list.append(int(item)) print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 8 |
[5, 6, 7, 8, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
Again, we initialized a list with five string values representing integers and stored it in the string_list
variable. After that, we also defined integer_list
and set it to an empty list. Next, we used a for
loop to iterate over each item in the string_list
. In each iteration, we used the int()
method to convert the current item from string to integer and passed it as an argument to the append()
method to populate the integer_list
.
Finally, we used the print()
method to display the entire integer_list
and another for
loop to show each element’s data type in integer_list
.
Using List Comprehension
Use list comprehension to convert string list to integer list in Python.
1 2 3 4 5 6 |
string_list = ['5', '6', '7', '8', '9'] integer_list = [int(item) for item in string_list] print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 8 |
[5, 6, 7, 8, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
Here, we used list comprehension to convert strings to integers. Learners find list comprehension challenging but let’s make it easy to understand. The [int(item) for item in string_list]
is the list comprehension that creates a list of integers by looping over every element, an item
in the string_list
.
For every item
in string_list
, the int(item)
was applied to convert item
from string to an integer value; this resulting integer value was added to a new list created by list comprehension. Once all elements in string_list
have been looped over and converted to integers, a new list of integers was returned by list comprehension, which we stored in the integer_list
variable for further use.
Lastly, we used print()
to show the entire integer_list
and for
loop to display each item’s data type in integer_list
.
If you have a question at this point and wonder if the map()
and lambda
functions are doing the same thing, then why have list comprehensions? Because it is a more readable and concise way to do the same thing as lambda
and map()
functions, particularly useful when we need to do additional operations on every item of the list.
Now, think of a situation where string_list
will have string values representing a mixture of integer and float values. How will you convert them to integer values? See the following solution to learn it.
1 2 3 4 5 6 |
string_list = ['5', '6.0', '7', '8.8', '9'] integer_list = [round(float(item)) for item in string_list] print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 8 |
[5, 6, 7, 9, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
This code is similar to the previous example, but for this solution, we used the float()
method to convert each item
to a floating-point number and passed it to the round()
method to convert it to the nearest integer number.
Remember, if you have an actual string value (a text value) in your
string_list
and use any of the solutions demonstrated yet in this article, you will end up with aValueError
. For example, you will getValueError
if you set a string list asstring_list = ['5', '6', 'text']
. Note that having an actual integer value ( such asstring_list = ['5', '6', 7]
) in yourstring_list
will not produce any error.
Using eval()
and ast.literal_eval()
Methods
Use the eval()
method with a list comprehension to convert string list to integer list in Python.
1 2 3 4 5 6 |
string_list = ['5', '6', '7', '8', '9'] integer_list = [eval(item) for item in string_list] print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 8 |
[5, 6, 7, 8, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
In the above example, we used the eval() method, which took an item
as a parameter; note that the item
is a string representation of an integer value such as '5'
. The eval()
returned its corresponding integer value because it evaluates the given expression and executes it if it is a legal Python statement.
Note that we will get NameError
if string_list
will have any actual string value such as ['5', 'text', '7', '8', '9']
and will get TypeError
if string_list
will have any actual integer value such as ['5', 6, '7']
.
Use the literal_eval()
method of the ast
module to convert string list to integer list in Python.
1 2 3 4 5 6 7 |
import ast string_list = ['5', '6', '7', '9'] integer_list = [ast.literal_eval(item) for item in string_list] print(integer_list) for item in integer_list: print(type(item)) |
1 2 3 4 5 6 7 |
[5, 6, 7, 9] <class 'int'> <class 'int'> <class 'int'> <class 'int'> |
This code snippet is similar to the previous one, but we used the ast.literal_eval() method to convert all list items from string to integer. Note that we will get ValueError
if an actual integer or float value is found in the string_list
such as ['5', 6, 6.7]
.
You might think that if both ast.literal_eval()
and eval()
functions evaluate the expressions, then why use them separately? Because they have some differences, which make one desirable over the other based on the use case.
The eval()
is Python’s built-in function to evaluate the specified string as Python expressions. It is used to evaluate any valid Python expression, such as statements, and can execute any arbitrary code; however, using eval()
can be harmful if used with untrusted inputs as it can run malicious code and result in security threats.
On the other side, the ast.literal_eval()
is safer than eval()
, which evaluates the specified string as a Python expression and returns an object only if it is a literal value (number, tuple, string, list, boolean, dictionary, or None). It does not evaluate statements or arbitrary code, which makes it a safer option while working with untrusted inputs. Evaluating literal values only makes the ast.literal_eval()
function less flexible than eval()
.
Considering performance, the eval()
is faster than the ast.literal_eval()
because it does not have to check whether the specified expression being evaluated is a literal value.
Now, the point is when to use which method? If you are sure that input is safe and you must evaluate a string as a Python expression, then you can proceed with the eval()
method. However, if you are not confident about the input, whether it is safe or not, and you only have to evaluate a literal value, then use ast.literal_eval()
.
Until this point, we have learned various solutions to convert string list to integer list, but none of them works on different variants of string_list
, such as ['5', 6, '7']
, ['5', 6, '7', 8.8]
, and `[‘5’, ‘6’, ‘text’]. So let’s define a function in the following section which can handle all these.
Further reading:
Using User-defined Function
To convert a string list to an integer list in Python:
- Use the
def
keyword to define a function. - Inside this function, defined in the first step:
- Use the
if
statement with thenot
operator to check if the item is empty. - If the item is not empty, use
float()
to convert it to float; otherwise, raiseValueError
. - If the item is converted to float, use
int()
to check if it can be represented as an integer. - If the float and integer values are the same, return the integer value; otherwise, float value.
- If the item can’t be converted to float, return it as it is.
- Use the
- Use the
map()
method to apply the function (defined in the first step) to every item in the string list. - Use
list()
method to convert map object (returned bymap()
) to list. - Use the
print()
method to display the converted list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def convert_string_list_to_integer_list(list_item): if not list_item: return list_item try: float_number = float(list_item) integer_number = int(float_number) return integer_number if float_number == integer_number else float_number except ValueError: return list_item string_list = ['some', '4', '9.8', 1, 8.8, 'text'] integer_list = list(map(convert_string_list_to_integer_list, string_list)) print(integer_list) |
1 2 3 |
['some', 4, 9.8, 1, 8.8, 'text'] |
If you also want to round the floating-point numbers to the nearest integers, you can use the round()
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def convert_string_list_to_integer_list(list_item): if not list_item: return list_item try: float_number = round(float(list_item)) integer_number = int(float_number) return integer_number if float_number == integer_number else float_number except ValueError: return list_item string_list = ['some', '4', '9.8', 1, 8.8, 'text'] integer_list = list(map(convert_string_list_to_integer_list, string_list)) print(integer_list) |
1 2 3 |
['some', 4, 10, 1, 9, 'text'] |
That’s all about convert String List to Integer List in Python.