![]() |
VOOZH | about |
First, let's understand arrays, It is a collection of items stored at contiguous memory locations. The basic idea is to store multiple items of the same type together which can be accessed by index/key (a number).
The contiguous memory of declared size is allocated on heap/stack and then the address of the element is calculated mathematically during run-time as:-
element address = (base address) + (element index * size of a single element)
where,
For example:
Int type requires 4-bytes (32-bit)
char type requires a 1-byte (8-bit)
long type requires 8-byte (64-bit) etc.
int arr[6] = {3, 4, 7, 9, 7, 1}
address of arr[0] (base address) = 0 x 61fe00
address of arr[3] (element address) = (base address) + (element index * size of a single element)
0 x 61fe00 + ( 3 * 4) = 0 x 61fe0c
Here, size of a single element is 4-bytes as it is int- type array.long long arr[6]={100, 12, 123, 899,124, 849}
address of arr[0] (base address) = 0x61fdf0
address of arr[3] (element address) = (base address) + (element index * size of a single element)
0x61fdf0 + ( 3 * 8) = 0x61fe08
Here, size of a single element is 8-bytes as it is long - type array.Note: Here addresses are of Hexadecimal form.
Let's see its implementation through a program to print the address of the array elements:
Base address:- 0x7ffc64918c30 Element address at index 3:- 0x7ffc64918c3c
Time Complexity : O(1), since accessing array index require constant O(1) time.
Auxiliary Space : O(1), since no extra space has been used.
In Python, indexing in arrays works by assigning a numerical value to each element in the array, starting from zero for the first element and increasing by one for each subsequent element. To access a particular element in the array, you use the index number associated with that element.
For example, consider the following code:
In this example, we define an array my_array that contains five elements. We then use indexing to access the first element (which has an index of 0) and the third element (which has an index of 2) and print their values to the console.
It's important to note that if you try to access an index that is outside the bounds of the array, you will get an "IndexError" exception. For example:
This code will raise an "IndexError" exception because there is no element in my_array with an index of 5.
Additionally, you can use negative indices to access elements from the end of the array. For example:
In this case, -1 corresponds to the last element in the array, -2 corresponds to the second-to-last element, and so on.