Python : Convert a list of strings (all int) to a list of integers

For converting a list of strings that are all integers, into a list of integers we use a built-in map function.
The map ( function, iterable, … ) function transforms all items in an iterable ( ex : lists, tuples, and strings ) by applying the function on them.
Thus we pass the below to the map function..

  • A built-in int (x, base=10) function that returns an integer object constructed from a number or a string x.
  • An iterable ( list of strings that are all integers ) returned by the input.split( ) function.

Below program accepts an input list of space seperated integers and converts them into a list of integers.

Python3 : Converting a list of integers in string format to a list of int

def main():

    _list_int = list(map(int, input("Enter string of space seperated integers : ").split()))
    print ("Numbers incremented...")
    for num in _list_int:
        print(num+1)

if __name__ == "__main__":
   main()

Output

Enter string of space seperated integers : 1 2 3 4 5 6
Numbers incremented...
2
3
4
5
6
7


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.