Index
Arrays in Python
An array is a collection of elements stored in a contiguous memory location. In Python, arrays are used to store multiple values of the same data type. Unlike lists, arrays require all elements to be of the same type.
Why Use Arrays Instead of Lists?
- Efficient memory usage: Arrays consume less memory compared to lists.
- Faster operations: Performing mathematical computations on arrays is faster.
Creating an Array in Python
Python does not have built-in support for arrays like C or Java. However, you can use the array
module or numpy
library.
Using the array
Module
To use arrays in Python, you must import the array
module.
import array
# Creating an integer array
arr = array.array('i', [10, 20, 30, 40, 50])
print(arr)
Output:
array('i', [10, 20, 30, 40, 50])
Accessing Array Elements
Just like lists, you can access elements using indexing.
print(arr[0]) # First element
print(arr[2]) # Third element
print(arr[-1]) # Last element
Output:
10
30
50
Looping Through an Array
Using for
Loop
for item in arr:
print(item)
Output:
10
20
30
40
50
Using while
Loop
i = 0
while i < len(arr):
print(arr[i])
i += 1
Output:
10
20
30
40
50
Modifying an Array
Adding Elements
append(value)
– Adds an element at the end.insert(index, value)
– Adds an element at a specific position.
arr.append(60) # Add at the end
arr.insert(2, 25) # Insert 25 at index 2
print(arr)
Output:
array('i', [10, 20, 25, 30, 40, 50, 60])
Removing Elements
remove(value)
– Removes the first occurrence of a value.pop(index)
– Removes the element at a specific index.
arr.remove(30) # Remove value 30
arr.pop(1) # Remove element at index 1
print(arr)
Output:
array('i', [10, 25, 40, 50, 60])
Finding an Element
You can search for an element using index()
, which returns the position of the element.
pos = arr.index(40)
print("Index of 40:", pos)
Output:
Index of 40: 2
Sorting an Array
Since the array
module does not have a built-in sort()
function, we can use sorted()
.
arr = array.array('i', [50, 10, 40, 30, 20])
sorted_arr = array.array('i', sorted(arr))
print(sorted_arr)
Output:
array('i', [10, 20, 30, 40, 50])
Using NumPy Arrays (Recommended for Large Data)
The NumPy library provides powerful arrays that are faster than the array
module
Installing NumPy
pip install numpy
Creating a NumPy Array
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr)
Output:
[10 20 30 40 50]
Advantages of NumPy Arrays
✅ Faster performance
✅ Supports mathematical operations
✅ Uses less memory