Convert String List to Integer List in Python

Convert String List to Integer List in Python

Using map() Method

Use the map() method with list() method to convert string list to integer list in Python.

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.

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 the list() method.

Using for Loop

Use the for loop to convert string list into integer list in Python.

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.

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.

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 a ValueError. For example, you will get ValueError if you set a string list as string_list = ['5', '6', 'text']. Note that having an actual integer value ( such as string_list = ['5', '6', 7]) in your string_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.

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.

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.

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 the not operator to check if the item is empty.
    • If the item is not empty, use float() to convert it to float; otherwise, raise ValueError.
    • 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 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 by map()) to list.
  • Use the print() method to display the converted list.

If you also want to round the floating-point numbers to the nearest integers, you can use the round() method:

That’s all about convert String List to Integer List in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *