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(): splits the string into sequence of elements means converts whitespace into commas (,), split function applicable only for 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 want to 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 number of elements: 2

Enter the numbers: 1 2

List is – [1, 2]

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

Note: IDE: PyCharm 2021.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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.