Skip to content
Related Articles

Related Articles

Python | Convert list of numerical string to list of Integers

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 05 Sep, 2022
Improve Article
Save Article

Many times, the data we handle might not be in the desired form for any application and has to go through the stage of preprocessing. One such kind of form can be a number in form of a string that too as a list in the list and we need to segregate it to be digit separated integers. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using list comprehension This problem can be dealt with list comprehension, as a shorthand for generic loops that we would require to run to perform this particular task by iterating each list’s each character of the string and converting to an integer. 

Python3




# Python3 code to demonstrate
# converting string list to integer list
# using list comprehension
 
# initializing list
test_list = [['24'], ['45'], ['78'], ['40']]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension
# converting string list to integer list
res = [[int(i) for i in sub] for i in test_list for sub in i]
 
# print result
print("The list after conversion : " + str(res))

Output

The original list : [['24'], ['45'], ['78'], ['40']]
The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]

Method #2: Using map() + list comprehension The task performed in the above function can also be reduced to include the map function which binds the conversion to integer to a function and rest of the task is performed by the list comprehension function itself. 

Python3




# Python3 code to demonstrate
# converting string list to integer list
# using list comprehension + map()
 
# initializing list
test_list = [['24'], ['45'], ['78'], ['40']]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + map()
# converting string list to integer list
res = [list(map(int, list(sub[0]))) for sub in test_list if sub]
 
# print result
print("The list after conversion : " + str(res))

Output

The original list : [['24'], ['45'], ['78'], ['40']]
The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]

Method #3: Using enumerate function

Python3




test_list = [['24'], ['45'], ['78'], ['40']]
res = [[int(i) for i in sub] for a,i in enumerate(test_list) for sub in i]
print(res)

Output

[[2, 4], [4, 5], [7, 8], [4, 0]]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!