Search code examples
pythonlistinputinteger

converting list of string to list of integer


How do I convert a space separated integer input into a list of integers?

Example input:

list1 = list(input("Enter the unfriendly numbers: "))

Example conversion:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]

Solution

  • map() is your friend, it applies the function given as first argument to all items in the list.

    map(int, yourlist) 
    

    since it maps every iterable, you can even do:

    map(int, input("Enter the unfriendly numbers: "))
    

    which (in python3.x) returns a map object, which can be converted to a list. I assume you are on python3, since you used input, not raw_input.