Python | Convert numeric String to integers in mixed List
Last Updated :
20 Apr, 2023
Sometimes, while working with data, we can have a problem in which we receive mixed data and need to convert the integer elements in form of strings to integers. This kind of operation might be required in data preprocessing step. Let's discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isdigit()
This is one way in which this task can be performed. In this, we check for each element of string whether it is a number using isdigit, and then converted to int if it is one. The iteration is using list comprehension.
Python3
# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# using list comprehension + isdigit()
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# Convert String numbers to integers in mixed List
# using list comprehension + isdigit()
res = [int(ele) if ele.isdigit() else ele for ele in test_list]
# printing result
print("List after converting string numbers to integers : " + str(res))
Output : The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #2 : Using map() + lambda + isdigit()
This task can also be performed using above functions. In this, we perform the task of iteration using map() and lambda function.
Python3
# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# using map() + lambda + isdigit()
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# Convert String numbers to integers in mixed List
# using map() + lambda + isdigit()
res = list(map(lambda ele : int(ele) if ele.isdigit()
else ele, test_list))
# printing result
print("List after converting string numbers to integers : " + str(res))
Output : The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.
Method #3 : Using isnumeric() method
Python3
# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# Convert String numbers to integers in mixed List
res = []
for i in test_list:
if i.isnumeric():
res.append(int(i))
else:
res.append(i)
# printing result
print("List after converting string numbers to integers : " + str(res))
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4 : Using try-except
Step-by-step approach :
- Initialize an empty list res.
- Use a for loop to iterate through each element of the test_list.
- Use a try-except block to check whether the current element can be converted to an integer using the int() function.
- If the conversion is successful, append the integer value to the res list using res.append(int(i)).
- If the conversion fails, simply append the original string value to the res list using res.append(i).
- Print the result list.
Below is the implementation of the above approach:
Python3
#Python3 code to demonstrate working of
#Convert String numbers to integers in mixed List
#using try-except
#initialize list
test_list = ["gfg", "1", "is", "6", "best"]
#printing original list
print("The original list : " + str(test_list))
#Convert String numbers to integers in mixed List
res = []
for i in test_list:
try:
res.append(int(i))
except:
res.append(i)
#printing result
print("List after converting string numbers to integers : " + str(res))
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method#5: Using a for loop
Here's the step-by-step algorithm for the approach used in this code, as well as its time and space complexity:
Algorithm:
- Initialize the original list of strings and integers.
- Initialize an empty list to store the converted integers.
- Loop through each element in the original list.
- Check if the element is a string representing an integer by using the isdigit() method.
- If the element is a string representing an integer, convert it to an integer and append it to the new list.
- If the element is not a string representing an integer, append the original element to the new list.
- Print the new list containing the converted integers.
Python3
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# create a new list to store the converted integers
int_list = []
# loop through each element in the original list
for ele in test_list:
# if the element is a digit, convert it to an integer and append to the new list
if ele.isdigit():
int_list.append(int(ele))
# otherwise, append the original element to the new list
else:
int_list.append(ele)
# print the new list
print("List after converting string numbers to integers : " + str(int_list))
#This code is contributed by Vinay Pinjala.#This code is contributed by Vinay Pinjala.
OutputList after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity:
The time complexity of this algorithm is O(n), where n is the length of the input list. This is because we loop through each element in the input list once, and each step in the loop takes constant time.
Auxiliary Space:
The space complexity of this algorithm is also O(n). We initialize an empty list of the same size as the input list to store the converted integers. This means that the space required is proportional to the size of the input list. However, the memory usage is relatively low as we are only storing integers and not creating new variables.
Method #6: Using a dictionary
This method uses a dictionary to map each digit string to its corresponding integer value. It then iterates through the list and replaces each digit string with its integer value using the get() method of the dictionary. For non-digit strings, it simply returns the original value.
Python3
# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# using dictionary
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# Convert String numbers to integers in mixed List
# using dictionary
num_dict = {str(i): i for i in range(10)}
res = [num_dict.get(ele, ele) for ele in test_list]
# printing result
print("List after converting string numbers to integers : " + str(res))
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(1) because the space used by the dictionary and the output list are both proportional to the size of the input list, which is a constant factor that does not depend on the size of the input.
Method#7: Using Recursive method.
Algorithm:
- Define a function convert_to_int(lst) that takes a list as input.
- Check if the list is empty, if it is, return an empty list.
- Check if the first element of the list is a digit using the isdigit() method.
- If it is a digit, convert it to an integer using the int() function and append to a new list.
- If it is not a digit, append the original element to the new list.
- Recursively call the function with the remaining elements of the list.
- Return the new list.
Python3
def convert_to_int(lst):
"""
Recursive function to convert string numbers to integers in a list.
"""
# base case: empty list
if not lst:
return []
# if the first element is a digit, convert it to an integer and append to the new list
if lst[0].isdigit():
return [int(lst[0])] + convert_to_int(lst[1:])
# otherwise, append the original element to the new list
else:
return [lst[0]] + convert_to_int(lst[1:])
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# call recursive function to convert string numbers to integers
int_list = convert_to_int(test_list)
# print the new list
print("List after converting string numbers to integers : " + str(int_list))
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
The time complexity of this algorithm is O(n), where n is the length of the input list. This is because we iterate over each element of the list exactly once.
The auxiliary space is also O(n), as we create a new list of the same size as the input list to store the converted elements.
Method#8: reduce function from the functools module:
Algorithm:
- Import the reduce function from the functools module and define a list test_list containing string and integer values.
- Use the reduce function to iterate through each element of the list and perform the following
- If the element is a numeric string, convert it to an integer and append it to the accumulator list. Otherwise, append the element itself to the accumulator list.
- The final accumulator list is the desired result, containing integers and non-numeric strings.
Python3
# Python program for the above approach
from functools import reduce
test_list = ["gfg", "1", "is", "6", "best"]
print("The original list : " + str(test_list))
res = reduce(lambda acc, i: acc + [int(i)]
if i.isnumeric() else acc + [i], test_list, [])
print("List after converting string numbers to integers : " + str(res))
# This code is contributed by Rayudu.
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity: O(n) where n is the number of elements in the list because the reduce function iterates through each element of the list once.
Space Complexity: O(n) because the accumulator list can potentially grow to the same size as the input list if all elements are numeric strings. However, in practice, the accumulator list is likely to be smaller than the input list since only a subset of elements is converted to integers.
Method#9: Using numpy:
Algorithm:
- Initialize an empty list "int_list" to store the converted integers
- Loop through each element "ele" in the original list "test_list"
- If the element is a digit, convert it to an integer and append to the "int_list"
- Otherwise, append the original element to the "int_list"
- Print the new list "int_list"
Python3
import numpy as np
import heapq
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# create a new list to store the
# converted integers
int_list = []
# loop through each element in the
# original list
for ele in test_list:
# if the element is a digit, convert it
# to an integer and append to the new list
if ele.isdigit():
int_list.append(int(ele))
# otherwise, append the original
# element to the new list
else:
int_list.append(ele)
# print the new list
print("List after converting string numbers to integers : " + str(int_list))
Output:
The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity: The time complexity of this algorithm is O(n), where n is the number of elements in the original list. This is because the algorithm loops through each element in the list only once.
Space Complexity: The space complexity of this algorithm is also O(n), as we are creating a new list of the same size as the original list to store the converted integers.
Method #10 : Using re.match()
Approach
- Initiate a for loop to traverse list of strings test_list
- Check whether the string is numeric using regular expression " ^[0-9]+$ " and method re.match()
- If yes convert the string to numeric using int() and append to output list res, if not append string as it is to res
- Display res
Python3
# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
# printing original list
print("The original list : " + str(test_list))
# Convert String numbers to integers in mixed List
import re
res=[]
for i in test_list:
if re.match('^[0-9]+$', i):
res.append(int(i))
else:
res.append(i)
# printing result
print("List after converting string numbers to integers : " + str(res))
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N) N - length of test_list
Auxiliary Space : O(N) N - length of res
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read