How do you calculate the length of a tuple in Python?
You can calculate the length of a tuple in Python using the built-in len()
function. Here are five examples demonstrating how to do this:
- Example with a simple tuple:
tuple1 = (1, 2, 3, 4, 5)
length = len(tuple1)
print("Length of tuple1:", length) # Output: Length of tuple1: 5
- Example with an empty tuple:
empty_tuple = ()
length = len(empty_tuple)
print("Length of empty_tuple:", length) # Output: Length of empty_tuple: 0
- Example with a tuple containing strings:
tuple_strings = ('apple', 'banana', 'cherry', 'date')
length = len(tuple_strings)
print("Length of tuple_strings:", length) # Output: Length of tuple_strings: 4
- Example with a tuple containing nested tuples:
nested_tuple = ((1, 2), ('a', 'b', 'c'), (True, False))
length = len(nested_tuple)
print("Length of nested_tuple:", length) # Output: Length of nested_tuple: 3
- Example with a tuple containing mixed data types:
mixed_tuple = ('apple', 3.14, True, [1, 2, 3])
length = len(mixed_tuple)
print("Length of mixed_tuple:", length) # Output: Length of mixed_tuple: 4
In each example, the len()
function is used to calculate the length of the respective tuple, returning the number of elements it contains.