Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
Now Reading
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Data structuring is a critical aspect of programming, and 2D Array in Python offers a versatile means of achieving it. In this guide, we will provide a detailed exploration of 2D arrays in Python. We will cover their creation, access, modification, common operations, and practical applications.
A 2D Array in Python is a two-dimensional data structure kept linearly in memory. It has two dimensions, which are the rows and columns, and hence symbolizes a matrix. By linear data structure, we imply that the items are stored in memory in a straight line, with each element related to the elements before and after it.
When working with 2D arrays, it's important to follow best practices to ensure your code is efficient, readable, and maintainable.
1. Plan Your Data Structure
Before creating a 2D Array in Python, it's essential to plan your data structure carefully. Consider the nature of your data and how it will be organized in rows and columns. A Valid 2D array is a suitable choice for your specific problem or not. Sometimes, alternative data structures like dictionaries or lists of lists might be more appropriate.
2. Use Descriptive Variable Names
Naming conventions are crucial for code readability. Use descriptive variable names that convey the purpose of your 2D Array in Python. For example, if your 2D array represents a game board, name it something like game_board rather than a generic name like matrix or arr.
code
# Good variable name
game_board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# Less descriptive variable name
matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
3. Handle Boundary Conditions Carefully
When accessing elements in a 2D array, be cautious about boundary conditions to avoid Python 2d list indexing errors. Ensure that your code accounts for edge cases, such as the first and last rows and columns.
code
# Check if a specific element is within bounds
if 0 <= row < num_rows and 0 <= col < num_cols:
value = array[row][col]
else:
print("Element is out of bounds.")
4. Use List Comprehensions
2d list Python comprehension is a concise and readable way to create and modify 2D arrays. They are useful when initializing a 2D array with specific values or performing transformations on its elements.
Example: Creating a 3x3 identity matrix using list comprehension
code
n = 3
identity_matrix = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
5. Leverage Libraries like NumPy
NumPy is a powerful library for numerical computing in Python. It offers efficient data structures and functions for working with arrays, including 2D arrays. When dealing with numerical data and complex operations, NumPy can significantly improve performance and simplify your code.
6. Document Your Code
Proper documentation is key to understanding complex 2D Array in Python operations, especially in collaborative projects. Use comments to explain the purpose of your 2D arrays, their dimensions, and any non-trivial operations.
7. Use Modularity
Break down your code into functions or methods that work with 2D arrays. It makes your code more modular and easier to understand.
code
def compute_sum_2d_array(array):
total = 0
for row in array:
total = sum(row)
return total
# Usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total_sum = compute_sum_2d_array(matrix)
Before diving into 2D arrays, it's essential to understand the creation of 1D lists in Python. A 1D list is a linear collection of elements. You can create a 1D list using various methods.
To create a 1D list, use a for loop to populate the list with elements. Here's an example:
code
# Creating a 1D list using a for-loop
my_list = []
for i in range(5):
my_list.append(i)
print(my_list)
List comprehensions provide a more concise and Pythonic way to create 1D lists. Here's an example:
code
# Creating a 1D list using list comprehension
my_list = [i for i in range(5)]
print(my_list)
You can create a 1D list containing the squares of numbers from 1 to 5 using list comprehension:
code
# Creating a 1D list of squares using list comprehension
my_list = [i**2 for i in range(1, 6)]
# Display the 1D list
print(my_list)
Output:
code
[1, 4, 9, 16, 25]
You can create a 1D list of even numbers within a specified range using list comprehension:
code
# Creating a 1D list of even numbers using list comprehension
my_list = [i for i in range(10) if i % 2 == 0]
# Display the 1D list
print(my_list)
Output:
code
[0, 2, 4, 6, 8]
Creating a 2-D List
In a 2-D list, each element is identified using two indices: one for the row and another for the column. There are various methods to create a 2-D list. Let's explore how to create a 2d list Python and populate it.
Creating a 2-D List using Nested Lists
In this approach, you first create an empty list, and then for each row, you create another list to represent the columns. Here's an example:
code
# Creating a 2-D list using nested lists
rows, cols = 3, 4
matrix = [] # Initialize an empty list to represent the 2-D list
for i in range(rows):
row = [] # Create an empty list for each row
for j in range(cols):
row.append(i * cols j) # Populate the row with elements
matrix.append(row) # Add the row to the 2-D list
# Display the 2-D list
for row in matrix:
print(row)
Output:
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
Cren ating 2D List Using Naive Method
Creating a 2d list Python using nested lists is one common method. However, there's a more concise way to achieve this using a nested list comprehension
Example: Creating a 2-D List using List Comprehension
List comprehension can generate the entire 2-D list in a single line of code. Here's an example:
code
# Creating a 2-D list using list comprehension
rows, cols = 3, 4
matrix = [[i * cols j for j in range(cols)] for i in range(rows)]
# Display the 2-D list
for row in matrix:
print(row)
Output:
code
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
To Access elements in a 2D Python array, you have to specify the row and column indices. For example, array[i][j] accesses the element at row i and column j.
# Accessing an element
element = matrix[1][2]
print("Accessing element (1, 2):", element)
# Modifying an element
matrix[0][0] = 42
print("Modified 2D array:")
for row in the matrix:
print(row)
Output:
code
Accessing element (1, 2): 6
Modified 2D array:
[42, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
Some of the common operations that you can perform on 2D arrays:
Python print 2d array as grid
To print a 2D array as a grid in Python, you can use nested loops to iterate through the rows and columns of the array and format the output as a grid.
Here's a simple example of Python print 2d array as grid:
# Sample 2D array
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the 2D array as a grid
for row in grid:
for element in row:
print(element, end="\t") # Use '\t' for tab separation between elements
print() # Start a new line for the next row
Output:
Copy code
1 2 3
4 5 6
7 8 9
# Finding the sum of elements in a 2D array
total = 0
for i in range(rows):
for j in range(cols):
total = matrix[i][j]
print("The Sum of elements in the 2D array:", total)
Output:
The sum of elements in the 2D array: 105
Transposing a 2D Array in Python means switching its rows and columns. This operation can be useful for various tasks, such as matrix operations. Here's how you can transpose a 2D array:
code
# Transposing a 2D array
transposed_matrix = [[matrix[j][i] for j in range(rows)] for i in range(cols)]
print("Transposed 2D array:")
for row in transposed_matrix:
print(row)
Output:
Transposed 2D array:
[42, 4, 8]
[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
# Finding the maximum value in a 2D array
max_value = matrix[0][0]
for i in range(rows):
for j in range(cols):
if matrix[i][j] > max_value:
max_value = matrix[i][j]
print("Maximum value in the 2D array:", max_value)
Output:
Maximum value in the 2D array: 42
# Searching for an element in a 2D array
target = 17
found = False
for i in range(rows):
for j in range(cols):
if matrix[i][j] == target:
found = True
break
if found:
print(f"{target} found in the 2D array.")
else:
print(f"{target} not found in the 2D array.")
Output:
17 not found in the 2D array.
2D arrays have a wide range of applications in various fields. Here are a few practical examples of how 2D arrays are used:
Images are represented as 2D arrays of pixels in image processing. Each pixel's color and intensity can be stored in a 2D Array in Python to applying various filters, transformations, and operations to manipulate the image.
In game development, 2D arrays are frequently used to represent game maps, levels, and grids. Game developers use 2D arrays to manage the layout of game objects, track player progress, and implement collision detection.
Data analysis covers working with tables of data, and 2D arrays are an ideal structure for this purpose. You can use 2D arrays to store and manipulate data from CSV files, databases, or other sources.
In mathematical applications, matrices are represented as 2D arrays. Linear algebra operations such as matrix multiplication, determinants, and eigenvalue calculations rely on 2D arrays.
To work with 2D arrays more efficiently and effectively, you can leverage advanced techniques and libraries. One such library is NumPy.
To use NumPy, you first need to install it (if not already installed) and import it:
code
import numpy as np
You can then create and manipulate 2D arrays with ease using NumPy.
For example, to create a 2D array with zeros:
code
# Creating a 2D array with NumPy
rows, cols = 3, 4
array = np.zeros((rows, cols))
print(array)
Output:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
2D arrays are a fundamental and versatile tool in Python for structuring and managing data efficiently. Mastering the creation and manipulation of 2D arrays allows programmers to work with structured data effectively across a wide array of applications. A solid understanding of 2D Array in Python can enable you to take on complex data-related tasks of 3D array Python with confidence and precision.
1. What are the challenges when working with 2D arrays?
Common challenges include handling boundary conditions, avoiding index errors, and efficiently traversing or searching through large 2D arrays.
2. Are 2D arrays memory-efficient in Python?
2D arrays in Python, especially when created with standard lists, can consume more memory than necessary due to Python's dynamic typing. Using NumPy can help improve memory efficiency.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...