How to Get the Array Size in Python

by Amber Viescas
Thinkstock/Comstock/Getty Images

Python, unlike other languages, does not implement a normal "length()" or "size()" method to read the size of an array -- e.g., "array.length()." Instead, it implements the len() method, which takes the array itself as a parameter. This method is identical between normal arrays, which are declared with "array.array(character)"; lists that are defined by square brackets "[]"; and tuples, which are defined by parentheses. Special object types, such as strings and trees, also implement this method.

Step 1

Locate the variable name for your array. For instance, if it was declared in a line "arr = [1, 2, 3];" the variable name would be "arr." Arrays can also be declared as "array.array('i')" for an array of integers.

Step 2

Reference the array's size as len(arr). Python interprets this as calling the method arr.__(len)__, which is a special internal method, implemented by most classes that have a length, that returns the array size.

Insert the reference into your code to access the array's size.

Tips

  • "arr.__len__()" is also accepted by Python, but it is harder to remember.

References

Photo Credits

  • Thinkstock/Comstock/Getty Images

About the Author

Amber Viescas is a 23-year-old freelancer who has been writing since 2009, penning articles for sites such as Nu Home Source. She has a Bachelor of Arts in computer science from Swarthmore College and has co-published a paper in the "Journal of Parallel and Distributed Computing."

More Articles

×