An Array is a fundamental structure present in various programming languages, including C, C++, Java, Python, R, and JavaScript, among others. Arrays enable the storage of multiple data elements. This concept revolves around memory allocation, specifically executed through dynamic memory allocation. For instance, one might declare an array as x[10], which allows for the storage of ten data elements within x. Essentially, an array serves as a container that is capable of holding a predetermined quantity of items, all of which must be of the same data type.
An array represents a concept for organizing several items of identical type in a cohesive manner, allowing for straightforward calculation of each element's position by merely adding an offset to the initial value. Utilizing arrays can significantly enhance efficiency by minimizing the overall code size. They are employed to hold numerous values within a single variable. For instance, if you possess a collection of items allocated to their respective variables in the following manner:
car1 = "Lamborghini"
car2 = "Bugatti"
car3 = "Koenigsegg"
If your goal is to iterate over a collection of cars to locate a particular one, utilizing an array would be beneficial. An array allows you to hold multiple values within a single variable, enabling efficient management of related data.
In Python, arrays can be managed through a module referred to as Array. This module is particularly beneficial when there is a need to work with specific data values. To grasp the concept of an array, it is essential to understand the following terms:
- Element - An element is defined as each individual item that is contained within an array.
- Index - The index is a numerical designation that indicates the position of an element within an array. This index is crucial for recognizing the location of the element in question.
Array Representation
An array can be declared in various ways and in different languages. The important points that should be considered are as follows:
- The index starts with 0.
- We can easily find any elements within this Array using the Index value.
- The length of the Array defines the capacity to store the elements. It is written like x[10], which means the length of the array x is specified by 10.
Array Operations
Some of the basic operations supported by an array are as follows:
- Traverse - It prints all the elements one by one.
- Insertion - It adds an element at the given index.
- Deletion - It deletes an element at the given index.
- Search - It searches for an element using the given index or by value.
- Update - It updates an element at the given index.
In Python, an Array can be established by incorporating the array module into your Python script.
Python Array Syntax
It has the following syntax:
from array import *
arrayName = array(typecode, [initializers])
Accessing Array Elements
We are able to retrieve the elements of the array by utilizing the corresponding indices associated with those elements.
Accessing Array Elements Example in Python
In this section, we provide an illustration of how to retrieve elements from an array by utilizing their index values in Python.
import array as arr
a = arr.array('i', [2, 4, 5, 6])
print("First element is:", a[0])
print("Second element is:", a[1])
print("Third element is:", a[2])
print("Fourth element is:", a[3])
print("Last element is:", a[-1])
print("Second last element is:", a[-2])
print("Third last element is:", a[-3])
print("Fourth last element is:", a[-4])
print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])
Output:
First element is: 2
Second element is: 4
Third element is: 5
Forth element is: 6
last element is: 6
Second last element is: 5
Third last element is: 4
Forth last element is: 2
2 4 5 6 6 5 4 2
Explanation:
In the example provided above, we have brought in an array, established a variable called "a" that contains the elements of the array, and displayed these elements by referencing them via their respective indices. In this scenario, we can effortlessly locate an element within the array by utilizing the array index, such as a[0], a[1], a[-1], among others.
How to change or add elements?
Arrays possess mutability, allowing for the modification of their elements in a manner akin to that of lists.
Python Example to Change or Add Elements in Array
Let's consider an example to illustrate how we can modify, insert, or substitute any element within an Array in Python.
import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
# changing the first element 1 to the value 0.
numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing the last element 10 to the value 8.
numbers[5] = 8
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# replace the value of 3rd to 5th element by 4, 6 and 8
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])
Output:
array('i', [0, 2, 3, 5, 7, 10])
array('i', [0, 2, 3, 5, 7, 8])
array('i', [0, 2, 4, 6, 8, 8])
Explanation:
In the preceding example, we imported an array and established a variable called "numbers," which contains the array's values. To modify or append elements to an array, we can specify the index of the array at which we wish to make changes or additions. In this instance, we referenced the index number of the elements that require modification and assigned a new value to replace the existing elements.
Why use Arrays in Python?
The use of arrays can significantly enhance efficiency. Arrays have the potential to minimize the overall code size. By utilizing an array, one can expedite problem-solving across various programming languages. Moreover, arrays facilitate dynamic memory allocation.
How to Delete Elements from an Array?
In Python, the elements of an array can be removed by utilizing the del statement. To eliminate a specific value from the array, we can reference the index of the desired element.
import array as arr
number = arr.array('i', [1, 2, 3, 3, 4])
del number[2] # removing third element
print(number) # Output: array('i', [1, 2, 3, 4])
Output:
At this point, we will proceed to compile the aforementioned code in Python. Once the compilation is completed successfully, we will execute the code. The output generated is as follows -
array('i', [10, 20, 40, 60])
Explanation:
In the preceding example, we have brought in an array and established a variable called "number" which holds the values from that array. In this instance, we are utilizing the del statement to eliminate the third element, which is [3], from the specified array.
Finding the length of an array
The length of an array is characterized by the total count of elements that the array contains. It yields an integer value that corresponds to the overall number of elements found within that array.
Syntax
Utilizing the syntax provided below, one can effortlessly determine the length of the specified Array.
len(array_name)
Array Concatenation
The + symbol allows us to effortlessly concatenate two arrays.
Python Array Concatenation Example
To illustrate the concept of array concatenation in Python, we will use a specific example.
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])
b=arr.array('d',[3.7,8.6])
c=arr.array('d')
c=a+b
print("Array c = ",c)
Output:
Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
Explanation
In the preceding example, we have established variables referred to as "a, b, c" which contain the values from an array.
Another Example:
Let's consider another example to Python Array.
import array as arr
x = arr.array('i', [4, 7, 19, 22]) # Initialize the array elements
print("First element:", x[0])
print("Second element:", x[1])
print("Second last element:", x[-1])
Output:
First element: 4
Second element: 7
Second last element: 22
Explanation:
In the preceding illustration, we initially imported an array and established a variable referred to as "x," which contains the value of the array. Subsequently, we displayed the array elements by utilizing the index value corresponding to each element within the array.
Conclusion
We have gained substantial insights into Arrays in Python. An array serves as a data structure designed to hold several elements of the same type collectively. This facilitates the determination of the index of each element by merely adding an offset to the initial value. Utilizing arrays in combination can significantly streamline the code, ultimately saving time by minimizing its overall size.
Arrays are utilized to hold several values within a single variable. We explored how to access an element from the array, as well as how to add, modify, or remove elements. Additionally, we learned how to determine the length of the array and the process of concatenation, which essentially refers to the act of merging arrays together.
Python Arrays FAQs
1. Does Python have built-in support for arrays?
No, Python does not include a native array data type. Rather, Python offers lists, which serve the purpose of dynamic arrays.
2. What is the difference between a Python list and an array?
A List has the capability to hold elements of various data types, indicating that it is heterogeneous in nature.
An array is capable of holding elements that are of the same data type, which indicates that it is homogeneous in nature. This characteristic contributes to its enhanced memory efficiency.
3. How do you create an array in Python?
To generate an array in Python, we begin by importing the array module. Here's an illustration:
import array as arr
numbers = arr.array('i', [1, 2, 3, 4, 5])
print(numbers)
Output:
array('i', [1, 2, 3, 4, 5])
4. What are type codes in the array module?
The Type codes are used to determine the data type of the elements in the array, such as:
- i: signed integer
- f: float
- d: double
5. How are arrays different from NumPy arrays?
Python Arrays: The Python Array provides a restricted set of capabilities and is limited to basic data types only.
NumPy array: It offers greater capabilities, facilitating mathematical computations, slicing functionalities, and broadcasting techniques. Additionally, it is more efficient compared to a standard Python array.