Contents
- 1 What is an Array in Python?
- 2 Array Vs List in Python
- 3 Creating an Array in PythonÂ
- 4 Accessing a Python Array Element
- 5 Basic Operations of Arrays in Python
- 6 2D Arrays in Python
- 7 Dynamic Array in Python
- 8 Array Index in Python
- 9 Array Programs in Python
- 10 Python Array vs List
What is an Array in Python?
An array is a facts structure which could comprise or preserve a fixed wide variety of factors that are of the same Python facts type. An array consists of an element and an index. Index in an array is the location in which an detail resides. All factors have their respective indices. Index of an array continually begins with zero.
not like different programming languages, including Java, C, C++, and more, arrays are not that famous in Python because there are numerous iterable records kinds in Python which might be bendy and rapid to use which include Python lists. however, arrays in Python are nevertheless utilized in positive instances. in this module, we can research all approximately all of the crucial components of arrays in Python , from what they’re to whilst they’re used.
Following is the list of topics covered in this Python module.
- Array Vs List in Python
- Creating an Array in Python
- Accessing a Python Array Element
- Basic Operations of Arrays in Python
- 2D Arrays in Python
- Dynamic Array in Python
- Array Input in Python
- Array Index in Python
- Array Programs in Python
- Python Array vs List
Array Vs List in Python
The simple distinction among arrays and lists in Python is that lists are bendy and might hold absolutely arbitrary records of any statistics type whilst arrays can best preserve statistics of the identical facts kind.
Arrays are taken into consideration useful in terms of memory performance, but they’re generally slower than lists. As noted above, the Python array module is not that popular to apply, but they do get used in positive instances such as:
Creating an Array in PythonÂ
The array module supports numeric arrays in Python. So to create arrays in Python we need to import the array module. Below is the syntax to create an array. Now to understand how to declare an array in Python, let’s look at the following python array example:
from array import *
arraname = array(typecode, [Initializers])
here, type code is what we use to define the sort of price that is going to be saved inside the array. a number of the common type codes used within the creation of arrays in Python are described in the following table.
Type code | Data Type | Description |
‘b’ | signed char | Signed integer (1 byte) |
‘B’ | unsigned char | Unsigned integer (1 byte) |
‘i’ | int | Signed integer (2 bytes) |
‘I’ | unsigned int | Unsigned integer (2 bytes) |
‘l’ | long | Signed integer (4 bytes) |
‘L’ | unsigned long | Unsigned integer (4 bytes) |
‘f’ | float | Floating point (4 bytes) |
‘d’ | double | Floating point (8 bytes) |
Now, let’s create a Python array using the above-mentioned syntax.
Example
import array arr = array.array('i', [1, 2, 3, 4, 5]) print(arr)
Output
array(‘i’, [1, 2, 3, 4, 5])
Accessing a Python Array Element
we will get right of entry to the elements of an array in Python the use of the respective indices of these elements, as shown inside the following instance
Example
import array
# Create an array of integers
arr = array.array(‘i’, [10, 20, 30, 40, 50])
# Access elements using indices
print(“Element at index 0:”, arr[0])
print(“Element at index 2:”, arr[2])
print(“Element at index 4:”, arr[4])
Output
Element at index 0: 10
Element at index 2: 30
Element at index 4: 50
Basic Operations of Arrays in Python
- Traverse of an Array in Python: Iterating among elements in an array is called traversing. we are able to without difficulty iterate through the elements of an array the usage of Python for loop as proven in the example underneath.
Example
import array
# Create an array of integers
arr = array.array(‘i’, [10, 20, 30, 40, 50])
# Traverse through the array elements
print(“Array elements:”)
for elem in arr:
print(elem)
Output
Array elements:
10
20
30
40
50
- Insertion of Elements in an Array in Python:Â Using this operation, we can add one or more elements to any given index.
Example
import array
# Create an array of integers
arr = array.array(‘i’, [10, 20, 30, 40, 50])
# Insert a new element at index 2
arr.insert(2, 25)
# Print the updated array
print(“Updated array after insertion:”)
for elem in arr:
print(elem)
Output
Updated array after insertion:
10
20
25
30
40
50
- Deletion of Elements in an Array in Python:Â Using this operation, we can delete any element residing at a specified index. We can remove any element using the built-in remove() method.
Example
import array
# Create an array of integers
arr = array.array(‘i’, [10, 20, 30, 40, 50])
# Delete the element at index 2
del arr[2]
# Print the updated array
print(“Updated array after deletion:”)
for elem in arr:
print(elem)
Output
Updated array after deletion:
10
20
40
50
- Searching Elements in an Array in Python:Â Using this operation, we can search for an element by its index or its value.
Example
import array
# Create an array of integers
arr = array.array(‘i’, [10, 20, 30, 40, 50])
# Element to search
search_elem = 30
# Search for the element in the array
for i, elem in enumerate(arr):
if elem == search_elem:
print(f”Element {search_elem} found at index {i}”)
break
else:
print(f”Element {search_elem} not found in the array”)
Output
Element 30 found at index 2
In the above example, we have searched for the element using the built-in index() method. Using index(3) returned the output 2 which means that 3 is at the index number 2 in array_1. If the searched value is not present in the array, then the program will return an error.
- Updating Elements in an Array in Python:Â Using this operation, we can update an element at a given index.
Example
import array
# Create an array of integers
arr = array.array(‘i’, [10, 20, 30, 40, 50])
# Update element at index 2
arr[2] = 35
# Print the updated array
print(“Updated array:”, arr)
Output
Updated array: array(‘i’, [10, 20, 35, 40, 50])
2D Arrays in Python
A 2D Array is basically an array of arrays. In a 2D array, the position of an element is referred to by two indices instead of just one. So it can be thought of as a table with rows and columns of data.
Here’s an example of creating and accessing elements of a 2D array using lists of lists:
Example
# Creating a 2D array using lists of lists
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Accessing elements of the 2D array
print(matrix[0][0])
print(matrix[1][2])
print(matrix[2][1])
Output
1
6
8
We can also create 2D arrays using the array module in Python. Here’s an example:
Example
import array
# Creating a 2D array using the array module
matrix = [array.array(‘i’, [1, 2, 3]),
array.array(‘i’, [4, 5, 6]),
array.array(‘i’, [7, 8, 9])]
# Accessing elements of the 2D array
print(matrix[0][0])
print(matrix[1][2])
print(matrix[2][1])
Output
1
6
8
Dynamic Array in Python
A dynamic array is similar to an array, but the distinction is that its size can be dynamically changed at runtime. The programmer doesn’t need to specify how huge an array could be, ahead.
The elements of a regular array occupy a contiguous block of memory, and as soon as created, the dimensions can’t be changed. A dynamic array can, as soon as the array is filled, allocate a larger chew of memory, replica the contents from the original array to this new area, and keep to fill the available slots.
Example
from array import array
# Creating a dynamic array of integers
dynamic_array = array(‘i’)
# Appending elements to the dynamic array
dynamic_array.append(10)
dynamic_array.append(20)
dynamic_array.append(30)
# Printing the dynamic array
print(“Dynamic Array:”, dynamic_array)
# Accessing elements by index
print(“Element at index 0:”, dynamic_array[0])
print(“Element at index 1:”, dynamic_array[1])
# Updating an element
dynamic_array[1] = 25
print(“Updated dynamic array:”, dynamic_array)
# Deleting an element
del dynamic_array[1]
print(“Dynamic array after deletion:”, dynamic_array)
Output
Dynamic Array: array(‘i’, [10, 20, 30])
Element at index 0: 10
Element at index 1: 20
Updated dynamic array: array(‘i’, [10, 25, 30])
Dynamic array after deletion: array(‘i’, [10, 30])
Array Index in Python
The index of a value in an array is the position of the value in the array. Calculating array indices in Python starts at 0 and ends at n-1; where n is the total number of elements in the array.
Element | Index |
10 | 0 |
20 | 1 |
30 | 2 |
40 | 3 |
50 | 4 |
Array Programs in Python
Let’s go through some common Array programs in Python.
Array Length in Python
Use the len() method to return the length of an array (the number of elements in an array).
Example
# Define the array
friends = [“Ramkrishna”, “Vishnu”, “Shubham Kashyap”, “Jitendra Sharma”]
# Get the length of the array
length = len(friends)
# Print the length
print(“Length of the array:”, length)
Output
Length of the array: 4
Sum of Array in Python
Example
# Define the array
numbers = [1, 2, 3, 4, 5]
# Initialize a variable to store the sum
sum_of_numbers = 0
# Iterate through each element and accumulate their values
for num in numbers:
sum_of_numbers += num
# Print the sum
print(“Sum of the array:”, sum_of_numbers)
Output
Sum of the array: 15
Sort Arrays in Python
Python provides a built-in function to sort arrays. The sort function can be used to sort the list in both ascending and descending order.
Example
# Input array
array = [3, 1, 4, 2, 5]
# Sort the array using sort() method
array.sort()
# Print the sorted array
print(“Sorted array using sort():”, array)
Output
Sorted array using sort(): [1, 2, 3, 4, 5]
Reverse Array in Python
Example
arr = [1, 2, 3, 4, 5]
reversed_arr = arr[::-1]
print(“Original array:”, arr)
print(“Reversed array:”, reversed_arr)
Output
Original array: [1, 2, 3, 4, 5]
Reversed array: [5, 4, 3, 2, 1]
Array Slice in Python
Example
import numpy as np
# Create a NumPy array
a = np.array([2, 4, 6])
# Create a slice of the array
b = a[0:2]
# Print the slice
print(b)
Output
[2 4]
List to Array in Python
Example
import numpy as np
# Create a list
my_list = [1, 2, 3, 4, 5]
# Convert the list to an array using numpy
my_array = np.array(my_list)
# Print the array
print(my_array)
print (type(my_array))
Output
[1 2 3 4 5]
<class ‘numpy.ndarray’>
Python Array vs List
Feature | Python List | Python Array (using array module) | Python Array (using numpy library) |
Definition | Collection of elements, ordered sequence | Collection of elements, ordered sequence | Collection of elements, ordered sequence |
Data Type | Supports heterogeneous data types | Supports homogeneous data types | Supports homogeneous data types |
Memory Efficiency | Less memory efficient | More memory efficient | More memory efficient |
Performance | Slower performance for large datasets | Faster performance for large datasets | Faster performance for large datasets |
Flexibility | Flexible, can contain any data type | Less flexible, must be of the same type | Less flexible, must be of the same type |
Access Time | Slower access time | Faster access time | Faster access time |
Implementation | Built-in Python data structure | Provided by the array module | Provided by the numpy library |