Taking space-separated integers user input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

Taking space-separated integers user input in Python #

To take space-separated integers from user input:

  1. Use the input() function to take multiple, space-separated integers.
  2. Use the str.split() function to split the string into a list.
  3. Use the int() class to convert each string in the list to an integer.
main.py
my_list = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in my_list] print(list_of_integers)

taking space separated integers user input

We used the input() function to take input from the user.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

Note that the input() function is guaranteed to return a string, even if the user enters an integer.
main.py
my_list = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in my_list] print(list_of_integers)

The str.split() method splits the string into a list of substrings using a delimiter.

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.
main.py
print('2 4 6 8'.split()) # 👉️ ['2', '4', '6', '8']

The last step is to use a list comprehension to convert the strings in the list to integers.

main.py
my_list = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in my_list] print(list_of_integers)
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we pass the current list item to the int() class to convert it to an integer.

Alternatively, you can use the map() function.

To take space-separated integers from user input:

  1. Use the input() function to take multiple, space-separated integers.
  2. Use the map() function to convert each string to an integer.
  3. Use the list() class to convert the map object to a list.
main.py
list_of_integers = list( map( int, input('Enter space-separated integers: ').split() ) ) print(list_of_integers)

We used the str.split() function to split the string of multiple, space-separated integers.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map function calls the int() class with each value in the list and converts each string to an integer.

The last step is to use the list() class to convert the map object to a list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.