How to take array input in Python | Example code

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

Example take array input in Python

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]

print(res)

Output:

How to take array input in Python

Another Example

Using raw_input is your helper here. 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 :")
    num_array.append(int(n))

print 'ARRAY: ',num_array

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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