Length

Introduction:

  • In Python, you can find the length of an array (or list) using the len() method. This method returns the number of elements in the array.

Syntax:

  • To get the length of an array cars, you use:

    python
    x = len(cars)
    

Example:

  • Let's return the number of elements in the cars array.

    python
    cars = ["Ford", "Volvo", "BMW"]
    x = len(cars)
    print(x)  
    • Output: 3

Note:

  • The length of an array is always one more than the highest array index. For example, if the array has 3 elements, its length is 3, and the highest index is 2.

Exercises:

  1. Find the Length of a List of Numbers:
    • Write a program to find the length of a list of numbers.

      python
      numbers = [10, 20, 30, 40, 50]
      length = len(numbers)
      print(length)
      • Output 5
  2. Find the Length of an Empty List:
    • Write a program to find the length of an empty list.

      python
      empty_list = []
      length = len(empty_list)
      print(length) 
      • Output 0

Summary:

  • In this tutorial, we learned how to use the len() method to return the length of an array. This is an essential skill when working with arrays in Python. Practice using the len() method to get comfortable with finding the length of arrays and lists!