Python Arrays
In Python, arrays are used to store multiple items of the same data type. Python does not have built-in support for arrays, but you can use lists or the array
module to work with arrays.
Example 1: Using Lists as Arrays
Create and access elements of an array using a list.
# Using lists as arrays
languages = ["Tamil", "English", "Hindi", "French"]
print("First Language:", languages[0])
print("All Languages:", languages)
First Language: Tamil
All Languages: ['Tamil', 'English', 'Hindi', 'French']
Example 2: Using the array
Module
Create an array of integers using the array
module.
# Using array module
import array as arr
numbers = arr.array('i', [1, 2, 3, 4, 5])
print("Numbers:", numbers)
print("First Number:", numbers[0])
Numbers: array('i', [1, 2, 3, 4, 5])
First Number: 1
Example 3: Adding and Removing Elements
Add and remove elements from an array.
# Adding and removing elements
numbers.append(6)
print("After Append:", numbers)
numbers.remove(3)
print("After Remove:", numbers)
After Append: array('i', [1, 2, 3, 4, 5, 6])
After Remove: array('i', [1, 2, 4, 5, 6])
Example 4: Looping Through an Array
Print all elements in the array.
# Looping through an array
for number in numbers:
print(number)
1
2
4
5
6
Example 5: Array Operations
Reverse the array and count occurrences of an element.
# Array operations
numbers.reverse()
print("Reversed Array:", numbers)
count = numbers.count(2)
print("Count of 2:", count)
Reversed Array: array('i', [6, 5, 4, 2, 1])
Count of 2: 1
Example 6: Multidimensional Arrays Using numpy
Create a 2D array using the numpy
library.
# Multidimensional arrays with numpy
import numpy as np
matrix = np.array([[1, 2], [3, 4], [5, 6]])
print("Matrix:\n", matrix)
Matrix:
[[1 2]
[3 4]
[5 6]]
Explanation: While Python lists can be used as arrays, the array
module provides more efficient storage for large arrays of the same data type. The numpy
library is used for advanced array operations and supports multidimensional arrays.