Skip to content

How to take array input in Python | Example code

  • by

Using the map() function and input() function we can take array input from the user in Python. Simply read inputs from the user using the map() function and convert them into the list (Array).

Using the input() function and converting the input into an array:

array = input("Enter space-separated elements: ").split()

Using a loop to take multiple inputs from the user and append them to a list:

array = []
n = int(input("Enter the number of elements: "))
for i in range(n):
    element = int(input("Enter element: "))

Using list comprehension and map() function:

array = list(map(int, input("Enter space-separated elements: ").split()))

Example take array input in Python

A simple example code enters N and then takes N number of elements. Use the spacebar to enter multiple entries.

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

# Read input
res = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]



How to take array input in Python

Another Example

Using raw_input is your helper here. The example code will basically look like this.

Note: This code works on Python 2

num_array = list()
num = raw_input("Enter how many elements you want:")

print 'Enter numbers in array: '

for i in range(int(num)):
    n = raw_input("num :")

print 'ARRAY: ',num_array

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 *