In this Python tutorial, I will show you, how to write a Python program to print the number of elements present in an array. We will see a complete example with the output.
Write a Python program to print the number of elements present in an array
In Python, arrays can be handled using built-in data types like a list or with an ‘array’ module. The task is simple: we want to create a Python program that prints out the number of elements present in an array. For this, we will use the built-in
len() function, which returns the number of items in an object.
Here is an example:
# create an array cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'] # print the number of elements in the array print(len(cities))
- The first line of code creates an array of cities. An array is just a list of items, and in Python, lists are created by enclosing the items in square brackets
. Here, our items are strings that represent the names of cities in the USA.
- The second line uses the built-in
len()function to count the number of elements in our array. The
len()function simply returns the number of items in an object. When we pass our array to this function, it counts the number of items and returns this count.
Let’s put it all together and write a complete Python program:
def count_elements(array): """ This function takes an array as an input and prints the number of elements in the array. """ print(len(array)) # create an array of cities cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'] # call the function and pass the cities array count_elements(cities)
In this script, we define a function
count_elements(array) that prints the number of elements in the provided array. We then create an array
cities, and finally, we call the function
count_elements(cities) to count the number of elements in our cities array.
When you run this script, it will output:
You can look at the screenshot below for the output:
In this tutorial, we’ve learned how to write a Python program to print the number of elements in an array using the built-in
You may also like:
- How to get values from json array in Python
- Python Array
- Split a String into an Array in Python
- Convert NumPy Array to List of Lists in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.