Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Take List of Tuples as Input in Python?
Next article icon

How to Take Array Input in Python Using NumPy

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

NumPy is a powerful library in Python used for numerical computing. It provides an efficient way to work with arrays making operations on large datasets faster and easier. To take input for arrays in NumPy, you can use numpy.array.

Taking Array Input Using numpy.array()

The most simple way to create a NumPy array is by converting a list of inputs into an array. It works well for scenarios where all elements are provided at once in a single line.

Python
import numpy as np  # Take input for the array as a space-separated string  val = input("Enter elements separated by space: ").split()  # Convert input elements to a NumPy array # Convert to integer array, change dtype as needed  arr = np.array(val, dtype=int)  print(arr) 

Output:

Enter elements separated by space: 1 2 3 4 5 
[1 2 3 4 5]

Explanation: Here, we first take input as a space-separated string split it into a list and then use numpy.array() to convert it into a NumPy array.

Let's explore other methods to create a NumPy array from user input:

Table of Content

  • Using List Comprehension with NumPy
  • Using numpy.fromiter()

Using List Comprehension with NumPy

We can also use list comprehension to create a NumPy array from user input. We can provide prompts for each input which makes it suitable for user-friendly input handling.

Python
import numpy as np  # Take input for the number of elements n = int(input("Enter the number of elements: "))  # Use list comprehension to collect elements val = [int(input(f"Enter element {i + 1}: ")) for i in range(n)]  # Convert to NumPy array arr = np.array(val) print(arr) 

Output:

Enter the number of elements: 6
Enter element 1: 23
Enter element 2: 45
Enter element 3: 21
Enter element 4: 45
Enter element 5: 23
Enter element 6: 12
[23 45 21 45 23 12]

Explanation: This code uses list comprehension to take n elements and then converts the resulting list into a NumPy array.

Using numpy.fromiter()

Another way to create a NumPy array is by using numpy.fromiter() which creates an array from an iterable. This method creates arrays directly without creating an intermediate list.

Python
import numpy as np  # Take input as space-separated values  val = input("Enter elements separated by space: ").split()  # Use fromiter() to create a NumPy array  arr = np.fromiter((int(x) for x in val), dtype=int)  print(arr) 

Output:

Enter elements separated by space: 12 18 87 83 86
[12 18 87 83 86]

Explanation: Here, we use a generator expression to create an iterable that numpy.fromiter() can convert to a NumPy array.

This method is suitable for processing large data inputs where conversion speed and efficiency matter.


Taking Input for Multi-dimensional Arrays

For multi-dimensional arrays, you can take input for each row separately and stack them.

Python
import numpy as np  # Input number of rows and columns rows = int(input("Enter the number of rows: ")) cols = int(input("Enter the number of columns: "))  # Empty list to hold the rows data = []  # Input each row for i in range(rows):     row = list(map(int, input(f"Enter row {i + 1} elements separated by spaces: ").split()))     data.append(row)  # Convert list of lists to NumPy array arr = np.array(data) print("2D NumPy Array:") print(arr) 

Output:

Enter the number of rows: 2
Enter the number of columns: 3
Enter row 1 elements separated by spaces: 1 2 3
Enter row 2 elements separated by spaces: 4 5 6
2D NumPy Array:
[[1 2 3]
[4 5 6]]




Next Article
How to Take List of Tuples as Input in Python?

A

anuragtriarna
Improve
Article Tags :
  • Python
  • Python Programs
  • Numpy
  • AI-ML-DS
  • Python numpy-program
Practice Tags :
  • python

Similar Reads

  • How to Input a List in Python using For Loop
    Using a for loop to take list input is a simple and common method. It allows users to enter multiple values one by one, storing them in a list. This approach is flexible and works well when the number of inputs is known in advance. Let’s start with a basic way to input a list using a for loop in Pyt
    2 min read
  • How to Take List of Tuples as Input in Python?
    Lists of tuples are useful data structures in Python and commonly used when you need to group related elements together while maintaining immutability within each group. We may need to take input for a list of tuples from the user. This article will explore different methods to take a list of tuples
    3 min read
  • How to take string as input from a user in Python
    Accepting input is straightforward and very user-friendly in Python because of the built-in input() function. In this article, we’ll walk through how to take string input from a user in Python with simple examples. The input() function allows us to prompt the user for input and read it as a string.
    3 min read
  • Take Matrix input from user in Python
    Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as 'rows' while the vertical entries are called as 'columns'. If a matrix has r number of rows and c number of columns then
    5 min read
  • How to Take a List as Input in Python Without Specifying Size?
    In many situations, we might want to take list as input without knowing the size in Python beforehand. This approach provides flexibility by allowing users to input as many elements as they want until a specified condition (like pressing Enter) is met. Let’s start with the most simple method to take
    2 min read
  • Convert list to Python array - Python
    We can use a number of approaches to convert a list into a Python array based on the requirements. One option is to use the array module, which allows us to create arrays with a specified data type. Another option is to use the numpy.array() method, which provides more features for working with arra
    2 min read
  • List As Input in Python in Single Line
    Python provides several ways to take a list as input in Python in a single line. Taking user input is a common task in Python programming, and when it comes to handling lists, there are several efficient ways to accomplish this in just a single line of code. In this article, we will explore four com
    3 min read
  • How to create an array of zeros in Python?
    Our task is to create an array of zeros in Python. This can be achieved using various methods, such as numpy.zeros(), which is efficient for handling large datasets. Other different methods are: Using the In-Build method numpy.zeros() methodUsing simple multiplication Using List comprehensionUsing i
    5 min read
  • Python String Input Output
    In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output. Input operations in PythonPython’s input() function allows us to get data from the
    3 min read
  • Slice a 2D Array in Python
    We are given a 2D array matrix and we have to Slice this matrix 2D array and return the result. In this article, we will see how we can Slice the 2D array in Python. Example Input : matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output : [[ 4, 5, 6]] Explanation : We can see that 2D array (matrix) is
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences