In Python, the length of an array can be obtained using the len() function. The len() function returns the number of elements in the array. In this article, we will see how we can find the length of Python Arrays.
Example:
arr = [1, 2, 3, 4, 5]
Length = 5
Python Array length
Python uses Lists instead of arrays. Both are similar and are used to work as an array. Let us see how we can find the length of a Python array.
Python Array Length using len() Method
The Python len() function can be used to find the length of an array in Python. The len() function returns the length of the list or array.
Python3
arr = [ 1 , 2 , 3 , 4 , 5 ] print ( len (arr)) |
Output:
5
Python Array Length using Array Module
Here we are going to use the Python array module for creating the array, and then len() function is used to obtain the length of the array.
Python3
# Python program to demonstrate # Creation of Array # importing "array" for array creations import array as arr # creating an array with integer type a = arr.array( 'i' , [ 1 , 2 , 3 ]) len (a) |
Output:
3
Python Array Length using Numpy Module
We can also use Python Numpy module to create an array and then use the len() function to calculate the length of the array.
Python3
# Python program to demonstrate # Creation of Array # importing "numpy" for array creations import numpy as np # creating an array a = np.array([ 1 , 2 , 3 ]) len (a) |
Output:
3
What is the Difference Between a Python Array and a List?
The main differences between a Python array and a list are as follows:
Parameters |
Python Array |
Python List |
---|---|---|
Data Type Constraint |
Python arrays are homogeneous, meaning they can only store elements of the same data type |
Python lists can store elements of different data types. |
Memory Efficiency |
Python arrays are generally more memory-efficient than lists. They are implemented as a contiguous block of memory |
Python lists are implemented as dynamic arrays with additional features, such as resizing and insertions/deletions. |
Supported Operations |
Python arrays offer basic operations such as indexing, slicing, appending, and element assignment. |
Python lists, being more flexible, support a wider range of operations, including insertions, deletions, sorting, reversing, and more. |
Performance |
Arrays can provide better performance due to their memory efficiency and the ability to leverage certain mathematical libraries in the case of a large collection of homogeneous elements for numerical computations. |
Lists, being more versatile, may have slightly lower performance in such scenarios |