Skip to content

How to take n number of inputs in Python | Example code

  • by

Use map() function and split() function to take n number of inputs in Python.

list(map(int, input().split()[:N]))
  • input(): takes user input.
  • split(): Splitting the string into a sequence of elements means converting whitespace into commas (,), a split function applicable only for the string data type.
  • map(): takes 2 arguments 1st one is a function and 2nd one is sequence of numbers.
  • list: this is the container to store the elements.
  • append(): adding elements at the end.

If the numbers are provided in the same line then you can use,

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

If inputs are in different lines then,

arr = [ int(input()) for i in range(n)]

Example take n number of inputs in Python

Simple example code.

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



How to take n number of inputs in Python

If the user wants to select how many numbers then enter.

n = int(input("Enter number of elements : "))

# Below line read inputs from user using map() function
a = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]

print("\nList is - ", a)


Enter the number of elements: 2

Enter the numbers: 1 2

List is – [1, 2]

Using a list comprehension: You can use a list comprehension to take n inputs and store them in a list:

n = int(input("Enter the number of inputs: "))
inputs = [input(f"Enter input {i + 1}: ") for i in range(n)]

print("You entered:", inputs)

Do comment if you have any doubts or suggestions on this Python input topic.

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

Your email address will not be published. Required fields are marked *