Python 3 – Tuple len() Method
In Python 3, tuples are an ordered and immutable sequence of elements that can contain any type of data. They are very similar to Python Lists with the main difference being that Lists are mutable while Tuples are immutable. This means that once a tuple is created, it can’t be changed or modified. Tuples are defined using parenthesis ( ) and elements are separated by commas.
The len() function is a Python built-in function that returns the number of elements in a container. In this article, we will talk about how to use the tuple len() method in Python 3.
Syntax of tuple len() method
The syntax of the tuple len() method in Python 3 is as follows:
len(tuple)
Where tuple is the tuple that we want to find the length of.
Here is an example of how to find the length of a tuple:
# Creating a tuple
my_tuple = ("apple", "banana", "cherry", "orange")
# Finding the length of the tuple
tuple_length = len(my_tuple)
# Printing the length of the tuple
print(tuple_length)
Output:
4
Example code
Let’s look at some examples of using the tuple len() method.
Example 1: Finding the length of an empty tuple
# Creating an empty tuple
my_tuple = ()
# Finding the length of the empty tuple
tuple_length = len(my_tuple)
# Printing the length of the empty tuple
print(tuple_length)
Output:
0
Example 2: Finding the length of a tuple with elements
# Creating a tuple with elements
my_tuple = (1, 2, 3, 4, 5)
# Finding the length of the tuple
tuple_length = len(my_tuple)
# Printing the length of the tuple
print(tuple_length)
Output:
5
Example 3: Finding the length of a tuple with nested tuples
# Creating a tuple with nested tuples
my_tuple = ((1, 2), (3, 4), (5, 6))
# Finding the length of the tuple
tuple_length = len(my_tuple)
# Printing the length of the tuple
print(tuple_length)
Output:
3
Example 4: Finding the length of a tuple with mixed data types
# Creating a tuple with mixed data types
my_tuple = (1, "apple", True, 3.14)
# Finding the length of the tuple
tuple_length = len(my_tuple)
# Printing the length of the tuple
print(tuple_length)
Output:
4
Conclusion
In this article, we discussed the Python 3 Tuple len() method which is used to find the length of a tuple. We saw the syntax of the tuple len() method and looked at some examples of using it. We hope this article has helped you understand how to use the tuple len() method in Python 3.