Arrays in Python allow you to store multiple values in a single variable. Learn how to create arrays using lists, the array module, and NumPy.
π¬What is an Array?
An
array is a linear data structure that stores elements in contiguous
memory locations.
Each element is accessed using an index, and all elements are of the same
data type.
π¬Key Features:
- Fixed
size
(in most languages like C/C++)
- Index-based
access
(starts from 0)
- Efficient
for reading elements
- Stored
in continuous memory
π¬Types of Arrays:
- One-Dimensional
Array:
Simple list of elements
- Two-Dimensional
Array:
Like a matrix (rows & columns)
- Multi-Dimensional
Array:
3D or more dimensions
π¬Array Syntax in Different Languages:
π’Python:
arr
= [10, 20, 30, 40]
print(arr[2]) # Output: 30
π’C:
int
arr[4] = {10, 20, 30, 40};
printf("%d",
arr[2]); // Output: 30
π’C++:
int
arr[] = {10, 20, 30, 40};
cout
<< arr[2]; // Output: 30
π’Java:
int[]
arr = {10, 20, 30, 40};
System.out.println(arr[2]);
// Output: 30
π¬Example Program (Python):
arr = [
1,
2,
3,
4,
5]
π# Insert
arr.insert(
2,
99)
# at index 2
print(arr)
# [1, 2, 99, 3, 4, 5]
π# Delete
arr.remove(
99)
print(arr)
# [1, 2, 3, 4, 5]
π# Search
print(
3
in arr)
# True
π# Update
arr[
1] =
20
print(arr)
# [1, 20, 3, 4, 5
π¬When to Use Arrays?
- When the size is known in advance.
- When you need fast access using index.
- For storing elements of same type.
No comments:
Post a Comment