Write a Python program to print the number of elements present in an array

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))
  1. 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.
  2. 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.

Full Example

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.

READ:  Python - Create Dictionary Of Tuples

When you run this script, it will output:

5

You can look at the screenshot below for the output:

write a python program to print the number of elements present in an array

Conclusion

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 len() function.

You may also like: