Python Program to Find the Length of a Tuple

Introduction

Tuples in Python are immutable sequences that can store a collection of items. Finding the length of a tuple, or the number of elements it contains, is a common operation when working with data structures. This tutorial will guide you through creating a Python program that finds the length of a tuple using the built-in len() function.

Example:

  • Input Tuple: ('apple', 'banana', 'cherry')
  • Output: The length of the tuple is 3

Problem Statement

Create a Python program that:

  • Takes a tuple as input.
  • Finds and displays the length of the tuple.

Solution Steps

  1. Create a Tuple: Initialize a tuple with some elements.
  2. Find the Length of the Tuple: Use the len() function to find the number of elements in the tuple.
  3. Display the Length: Use the print() function to display the length of the tuple.

Python Program

# Python Program to Find the Length of a Tuple
# Author: https://www.rameshfadatare.com/

# Step 1: Create a tuple with elements
my_tuple = ('apple', 'banana', 'cherry', 'date', 'elderberry')

# Step 2: Find the length of the tuple using the len() function
tuple_length = len(my_tuple)

# Step 3: Display the length of the tuple
print("The length of the tuple is:", tuple_length)

Explanation

Step 1: Create a Tuple with Elements

  • A tuple my_tuple is created with several elements: 'apple', 'banana', 'cherry', 'date', and 'elderberry'. Tuples are defined using parentheses ().

Step 2: Find the Length of the Tuple Using the len() Function

  • The len() function is used to calculate the number of elements in the tuple my_tuple. The result is stored in the variable tuple_length.

Step 3: Display the Length of the Tuple

  • The print() function is used to display the length of the tuple, which is the value of tuple_length.

Output Example

Example Output:

The length of the tuple is: 5

Additional Examples

Example 1: Empty Tuple

# Empty tuple
empty_tuple = ()
tuple_length = len(empty_tuple)
print("The length of the empty tuple is:", tuple_length)

Output:

The length of the empty tuple is: 0

Example 2: Tuple with Mixed Types

# Mixed-type tuple
mixed_tuple = ('apple', 42, 3.14, 'banana')
tuple_length = len(mixed_tuple)
print("The length of the mixed-type tuple is:", tuple_length)

Output:

The length of the mixed-type tuple is: 4

Conclusion

This Python program demonstrates how to find the length of a tuple using the len() function. The len() function is a straightforward and efficient way to determine the number of elements in any sequence, including tuples. Understanding how to calculate the length of a tuple is essential for managing and analyzing data stored in these immutable sequences in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top