Hey, readers. Hope you all are doing well. In this article, we would be primarily focusing on Variants of Python Array Declaration.
What is a Python Array?
As we all know, Python offers various data structures to manipulate and deal with the data values.
When it comes to ARRAY as a data structure, Python does not offer a direct way to create or work with arrays. Rather, it provides us with the below variants of Array:
- Python Array Module: The Array module contains various methods to create and work with the values.
- Python List: List can be considered as a dynamic array. Moreover, heterogeneous elements can be stored in Lists, unlike Arrays.
- Python NumPy Array: NumPy arrays are best suitable for mathematical operations to be performed on a huge amount of data.
Having understood about Python Array, let us now understand the ways through which we can declare an array in Python.
Python Array Declaration – Variants of the Python Array
In the below section, we will understand the techniques through which we can declare an array using the variants of Python array.
Type 1: Python Array module
Python Array module
contains array() function
, using which we can create an array in the python environment.
Syntax:
array.array('format code',[data])
format_code
: It represents the type of elements to be accepted by an array. The code ‘i’ represents numeric values.
Example:
import array
arr = array.array('i', [10,20,30,40,50])
print(arr)
Output:
array('i', [10, 20, 30, 40, 50])
Type 2: Python List as an Array
Python list
can be used to dynamically create and store the elements like an array.
Syntax:
list = [data]
Example:
lst = [10,20,30,40, 'Python']
print(lst)
Output:
[10, 20, 30, 40, 'Python']
As mentioned above, elements of various data types can be stored together in List.
Type 3: Python NumPy array
NumPy module
contains various functions to create and work with array as a data structure.
The numpy.array() function
can be used to create single as well as multi-dimensional array in Python. It creates an array object as ‘ndarray’.
np.array([data])
Example: Array creation using numpy.array() function
import numpy
arr = numpy.array([10,20])
print(arr)
Output:
[10 20]
Further, we can use numpy.arange() function
to create an array within the specific range of data values.
numpy.arange(start,stop,step)
start
: The starting element of the array.end
: The last element of the array.step
: The number of interval or steps between array elements.
Example:
import numpy
arr = numpy.arange(1,10,2)
print(arr)
Output:
[1 3 5 7 9]
Conclusion
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.