A 2D array (two-dimensional array) is a data structure that stores data in the form of rows and columns. It is used to represent data in a grid format.
Python provides us a lot of ways to take a 2d array as input. In this blog, we will learn all of these methods in more detail.
Table of Contents:
To take a 2d array as input, we can use a nested loop. One for iterating the row, and the other for iterating the column. This is the easiest and most commonly used method by beginner developers.
Code:
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
for i in range(rows):
row = []
for j in range(cols):
value = int(input(f"Enter element at position ({i},{j}): "))
row.append(value)
matrix.append(row)
print("2D Array (Matrix):")
for i in range(rows):
for j in range(cols):
print(matrix[i][j], end=" ")
print()
Output:
Explanation: Here, we have run two for loops, one for iterating rows and the other for iterating columns. And stored the value in a matrix array. Also, we have printed the values using two loops.
We can use list comprehension, which makes the code more readable and simple. In Python, List is a data type in which we can store integers, floats, strings, etc. We can access the list items with the help of an index.
Code:
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = [[int(x) for x in input().split()] for _ in range(rows)]
print("2D Array (Matrix):")
for row in matrix:
print(*row)
Output:
Explanation: The above code takes rows of lines of space-separated values, where [int(x) for x in input().split()] converts each line into a list of integers. Finally, the outer list will convert the array into a 2d array(matrix).
NumPy provides powerful tools and methods for efficiently handling array operations. To take a 2d array as input using NumPy, we need to use the numpy.array() function to convert the input into a NumPy array.
Code:
import numpy as np
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = np.array([list(map(int, input().split())) for _ in range(rows)])
print("2D Array (Matrix):")
print(matrix)
Output:
Explanation: The above code uses the list to take rows lines of space-separated input, and it converts each line into a list of integers using map(int, input().split()). The np.array() function then converts the list of lists into a NumPy 2D array (matrix).
Conclusion
A 2d array is used to store data in the form of rows and columns. Matrix and Grid are examples of 2d array data structures. Here we have learned how we can take a 2d array as input in Python. Python provides us multiple ways to do this task. If you want to become a Python expert, you should refer to our Python course.
These resources provide a beginner’s guide to Python, concentrating on syntax structure, fundamental operators, and essential programming logic.
Magic Method in Python – Learn about magic methods in Python through clear examples.
Elif in Python – Delve into the use of the elif statement in Python, supported by practical examples.
Break and Continue – Discover how break and continue work in Python, illustrated with helpful examples.
Python Reserved Words – Covers Python reserved words and demonstrates their use with examples.
Python Interactive Mode Chevron – Overview of Python’s interactive mode and chevron prompt with real-world examples.
Global Variable in Function – Explore how global variables behave inside functions in Python, with detailed examples.
Python Yield Keyword – Understand the yield keyword in Python and how it functions, supported by sample code.
Python Tuple – Take a closer look at tuples in Python, with explanations and practical examples.
Set Attribute Error – Learn what causes a setattr error in Python and how to handle it, using examples.
FAQs
1. How do you access an element in 2D array?
You can access elements in a 2D array using index of the row and column.
Eg: matrix[row][col], Here row is the index of row, and col is the index of column.
2. What is a 2D array in Python?
A 2d array is a data structure that is used to represent the elements in the form of rows and columns.
3. How to create a 2D array in Python?
To create a 2d array in Python, we can use a list or numpy array(numpy.array()).
4. What is an array in Python?
An array in Python is a data structure that stores multiple values in an ordered way. We can access the elements with the help of an index.
5. How many types of arrays are there in Python?
There are 4 types of arrays in Python:
- Fixed Size Array
- Dynamic Sized Array
- 1-Dimensional Array
- Multi-Dimensional Array