PyDataAlgo
Exploring Arrays in Python: Part 2
purya behzadpur
Two-Dimensional Array in Python:
A two-dimensional array in Python is essentially
a list of lists. It's a collection of elements
organized in a matrix or grid format, where each
element is identified by two indices instead of
one. This structure allows for the representation
of tables, matrices, and other 2D structures.
WhyUseIt:
Structured Data: Excellent for representing matrices,
tables,andgrids.
Efficient Storage: Provides a tabular structure for
efficientdatastorage.
Matrix Operations: Useful for linear algebra and
numericalcomputing.
Image Processing: Commonly employed for pixel data in
imageprocessing.
Operations on 2D Arrays:
Creation:
Time Complexity: O(m * n) where m is the number of
rows and n is the number of columns. This is because
each element needs to be initialized.
Space Complexity: O(m * n) as it requires storage for
each element.
Accessing an Element:
Time Complexity:
At the end: O(1) for each element.
At the beginning or middle: O(m * n) as it may
involve shifting elements.
Space Complexity: O(1) for each element.
Searching:
Time Complexity: O(m * n) in the worst case. In the
average case, it could be O(m + n) if the target is in the
last row or column.
Space Complexity: O(1) as it doesn't require additional
space.
Traversing:
Time Complexity: O(m * n) since every element needs to
be visited.
Space Complexity: O(1) as no additional space is used.
Deletion:
Time Complexity:
For a specific element: O(m * n) as it may involve
shifting elements.
For a complete row or column: O(m * n) as it
involves copying the remaining elements.
Space Complexity: O(1) for each element.
NumPy Library:
NumPy provides a powerful array class for
working with multi-dimensional arrays.
For Creation :
Time Complexity: O(m * n) where m is the
number of rows and n is the number of columns.
Each element needs to be initialized.
Space Complexity: O(m * n) as it requires
storage for each element.
For Deletion:
Time Complexity:
For a specific element: O(m * n) as it may
involve shifting elements.
For a complete row or column: O(m * n) as it
involves copying the remaining elements.
Space Complexity: O(m * n) as it creates a new
array.
When to Use/Avoid an Array:
Use Arrays When:
Random Access is Important: O(1) time complexity.
Fixed Size is Acceptable: Efficient storage with O(1)
access.
Avoid Arrays When:
Dynamic Resizing is Needed: O(n) time complexity for
resizing.
Key-Value Pairs are Required: For scenarios where data
retrieval is based on keys rather than indices.
Complex Operations are Frequent: If the operations on
elements involve more than basic access or modification.