Change language

Python | Convert list of numeric string to list of integers

|

Method # 1: Using List Comprehension
This problem can be solved by using list comprehension as a reduction in the general cycles that we would have to go through to accomplish this particular task, repeating each the line character of each list and converting to an integer.

# Python3 demo code
# converting a list of strings to a list of integers
# using comprehension list

  
# initializing list

test_list = [[ ’24’ ], [ ’45’ ], [ ’ 78’ ], [ ’40’ ]]

 
# print original list

print ( "The original list:" + str (test_list))

 
# using comprehension list
# converting string list to list of integers

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
Problem executed in the above function can also be scaled down to include a display function that associates the conversion to integer with the function and the rest of the task is done the list comprehension function itself.

# Python3 demo code
# convert a list of strings to a list integers
# using a list comprehension + map ()

 
# initializing list

test_list = [[ ’24’ ], [ ’45’ ], [ ’ 78’ ] , [ ’40’ ]]

  
# print original list

print  ( "The original list:" + str (test_list))

 
# using comprehension list + map ()
# convert a list of strings to a list of integers

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]] 

Python | Convert list of numeric string to list of integers Python functions: Questions

Python | Convert list of numeric string to list of integers String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method