Skip to content

How to take space-separated integer input in Python 3 | Example code

  • by

Use input(), map(), and split() functions to take space-separated integer input in Python 3. You have to use list() to convert the map to a list.

list(map(int,input().split())) 

Where:

  • input() accepts a string from STDIN.
  • split() splits the string about the whitespace character and returns a list of strings.
  • map() passes each element of the 2nd argument to the first argument and returns a map object

For example, take space-separated integer input in Python 3

Simple example code stage user multiple integers input, each separated space.

print("Enter the numbers: ")

inp = list(map(int, input().split()))

print(inp)

Output:

How to take space-separated integer input in Python 3

Here is another example of code

# Take space-separated integer input from the user
input_string = input("Enter space-separated integers: ")

# Split the input string into individual elements
input_list = input_string.split()

# Convert each element into an integer
numbers = [int(num) for num in input_list]

print(numbers)

In this example, the user is prompted to enter space-separated integers. After the input is captured, it is split into a list of substrings using split(). Then, a list comprehension is used to convert each substring into an integer. Finally, the resulting list of integers is printed.

Comment if you have any doubts or suggestions on this Python input program.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading