Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Converting all strings in list to integers

Python | Converting all strings in list to integers

Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of strings to integers is quite common in the development domain. Let’s discuss a few ways to solve this particular problem. 

Converting all strings in list to integers Using eval()

Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer.

Python3




lis = ['1', '-4', '3', '-6', '7']
res = [eval(i) for i in lis]
print("Modified list is: ", res)


Output:

Modified list is: [1, -4, 3, -6, 7]

Converting all strings in list to integers Naive Method

This is the most generic method that strikes any programmer while performing this kind of operation. Just looping over the whole list and converting each string of the list to int by type casting. 

Python3




test_list = ['1', '4', '3', '6', '7']
 
# using loop
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:

Modified list is: [1, 4, 3, 6, 7]

Converting all strings in list to integers Using list comprehension 

This is just a kind of replica of the above method, just implemented using list comprehension, a kind of shorthand that a developer looks for always. It saves the time and complexity of coding a solution. 

Python3




test_list = ['1', '4', '3', '6', '7']
 
# 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:

Modified list is : [1, 4, 3, 6, 7]

Converting all strings in list to integers Using map() 

This is the most elegant, pythonic, and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them. 

Python3




test_list = ['1', '4', '3', '6', '7']
 
# using map() to
# perform conversion
test_list = list(map(int, test_list))
 
# Printing modified list
print("Modified list is : " + str(test_list))


Output:

Modified list is : [1, 4, 3, 6, 7]

Converting all strings in list to integers List of strings with mixed integer representations

Here, we will first convert each string to a float first and then we will convert it into an integer by using the round() function, otherwise, it will throw error.

Python3




lis = ['1.1', '4', '3.5', '6.7', '7.2']
res = [round(float(i)) for i in lis]
print("Modified list is: ", res)


Output:

Modified list is: [1, 4, 4, 7, 7]

Converting all strings in list to integers Using the ast.literal_eval() function from the ast module

Another approach that can be used to convert a list of strings to a list of integers is using the ast.literal_eval() function from the ast module. This function allows you to evaluate a string as a Python literal, which means that it can parse and evaluate strings that contain Python expressions, such as numbers, lists, dictionaries, etc.

Here is an example of how to use ast.literal_eval() to convert a list of strings to a list of integers:

Python3




import ast
 
# Initialize list of strings
test_list = ['1', '4', '3', '6', '7']
 
# Convert strings to integers using ast.literal_eval()
test_list = [ast.literal_eval(s) for s in test_list]
 
# Print resulting list
print("Modified list:", test_list)
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

Modified list: [1, 4, 3, 6, 7]

The time complexity of using the ast.literal_eval() function from the ast module to convert a list of strings to a list of integers is O(n), where n is the length of the list. This means that the time required to execute this approach is directly proportional to the size of the input list.

In terms of space complexity, this approach has a space complexity of O(n), because it creates a new list of integers that is the same size as the input list. 

Converting all strings in list to integers Using numpy.array() function

  1. Define a list of strings
  2. Convert the list to a numpy array of type int using the numpy.array() function
  3. Convert the numpy array back to a list using list() function
  4. Print the modified list

Python3




import numpy as np
  
# Define list of strings
my_list = ['1', '4', '3', '6', '7']
  
# Convert list to numpy array of type int
my_array = np.array(my_list, dtype=int)
  
# Convert numpy array back to list
modified_list = list(my_array)
  
# Print modified list
print("Modified list is: ", modified_list)


Output:

Modified list is:  [1, 4, 3, 6, 7]

Time Complexity: The time complexity of this approach is O(n), where n is the length of the list. The numpy.array() function takes O(n) time to create a new array, and the list() function takes O(n) time to convert the array back to a list.

Space Complexity: The space complexity of this approach is O(n), because it creates a new numpy array of type int that is the same size as the input list.

Approach: Using the json.loads() function:

Algorithm:

  1. Create a list of strings test_list with the values [‘1’, ‘4’, ‘3’, ‘6’, ‘7’]
  2. Use the join() method to join the strings in test_list together with commas, resulting in the string ‘1,4,3,6,7’
  3. Add square brackets around the resulting string, resulting in the string ‘[1,4,3,6,7]’
    Use the loads() method from the json library to parse the string as a JSON array, resulting in the list [1, 4, 3, 6, 7]
  4. Assign the resulting list to new_list
  5. Print the string “Modified list is : ” followed by the string representation of new_list

Python3




import json
 
test_list = ['1', '4', '3', '6', '7']
new_list = json.loads('[' + ','.join(test_list) + ']')
print("Modified list is : " + str(new_list))
#This code is contributed by Vinay pinjala


Output

Modified list is : [1, 4, 3, 6, 7]

The time complexity: O(n), where n is the length of test_list. This is because the join() method takes O(n) time to concatenate the strings, and the loads() method takes O(n) time to parse the resulting string.

The space complexity: O(n), since the resulting list takes up O(n) space in memory.

Converting all strings in list to integers using re module 

 step-by-step algorithm for the regular expression approach to extract numerical values from a list of strings

  1. Define an input list of strings.
  2. Define a regular expression pattern to match numerical values in the strings.
  3. Initialize an empty list to store the converted numerical values.
  4. Iterate over each string in the input list.
  5. Use the regular expression pattern to search for a numerical value in the string.
  6. If a match is found, extract the matched substring and convert it to a float.
  7. Append the converted value to the output list.
  8. Once all strings in the input list have been processed, return the output list.

Python3




import re
 
# Define the input list
lis = ['1', '-4', '3', '-6', '7']
 
# Define a regular expression pattern to match numerical values
pattern = re.compile(r'-?\d+(?:\.\d+)?')
 
# Initialize an empty list to store converted values
res = []
 
# Iterate over each string in the input list
for s in lis:
    # Use the pattern to search for a numerical value in the string
    match = pattern.search(s)
    # If a match is found, extract the matched substring and convert it to a float
    if match is not None:
        res.append(int(match.group()))
 
# Print the modified list of converted values
print("Modified list is: ", res)


Output

Modified list is:  [1, -4, 3, -6, 7]

Time complexity: The time complexity of this approach is O(nm), where n is the number of strings in the input list and m is the maximum length of any string in the list. The regular expression pattern needs to be applied to each string in the list, which takes O(m) time in the worst case. Therefore, the overall time complexity is O(nm).
Auxiliary space complexity: The auxiliary space complexity of this approach is O(k), where k is the number of numerical values in the input list. We need to store each converted numerical value in the output list, which requires O(k) space. In addition, we need to store a regular expression object, which requires constant space. Therefore, the overall auxiliary space complexity is O(k).

RELATED ARTICLES

Most Popular

Recent Comments