Hey, folks! I hope you all are doing well. In this article, we will be unveiling 3 variants of Array length in Python.
As we all know, Python does not support or provide us with the array data structure in a direct manner. Instead, Python serves us with 3 different variants of using an Array data structure here.
Let us go first go through the different ways in which we can create a Python array.
Further, in the upcoming sections, we would be discussing about use of Python len() method to fetch the length of array in each of the variants.
Finding the Array Length in Python using the len() method
Python provides us with the array data structure in the below forms:
We can create an array using any of the above variants and use different functions to work with and manipulate the data.
Python len() method enables us to find the total number of elements in the array/object. That is, it returns the count of the elements in the array/object.
Let us now understand the way to find out the length of an array in the above variants of Python array.
Finding the Length of a Python List
Python len() method can be used with a list to fetch and display the count of elements occupied by a list.
In the below example, we have created a list of heterogeneous elements. Further, we have used len() method to display the length of the list.
lst = [1,2,3,4,'Python'] print("List elements: ",lst) print("Length of the list:",len(lst))
List elements: [1, 2, 3, 4, 'Python'] Length of the list: 5
Finding the Length of a Python Array
Python Array module helps us create array and manipulate the same using various functions of the module. The len() method can be used to calculate the length of the array.
import array as A arr = A.array('i',[1,2,3,4,5]) print("Array elements: ",arr) print("Length of array:",len(arr))
Array elements: array('i', [1, 2, 3, 4, 5]) Length of array: 5
Finding the Length of a Python NumPy Array
As we all know, we can create an array using
NumPy module and use it for any mathematical purpose. The len() method helps us find out the number of data values present in the NumPy array.
import numpy as np arr = np.arange(5) len_arr = len(arr) print("Array elements: ",arr) print("Length of NumPy array:",len_arr)
Array elements: [0 1 2 3 4] Length of NumPy array: 5
By this we have come to the end of this topic. Feel free to comment below, in case you come across any question. Till then, Happy Learning!