Python Tuple len() Method



The Python Tuple len() method returns the number of elements in the tuple.

A tuple is a collection of python objects that are separated by commas which are ordered and immutable. Tuples are sequences, just like lists. The difference between tuples and lists are: tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

Syntax

Following is the syntax of Python Tuple len() method −

len(tuple)

Parameters

  • tuple − This is a tuple for which number of elements are to be counted.

Return Value

This method returns the number of elements in the tuple.

Example

The following example shows the usage of Python Tuple len() method. Here we are creating two tuples 'tuple1' and 'tuple2'. The 'tuple1' contains the elements: 123, 'xyz', 'zara' and the 'tuple2' contains the elements: 456, 'abc'. Then the length of the tuples are retrieved using the len() method.

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))

When we run above program, it produces following result −

First tuple length :  3
Second tuple length :  2

Example

Here, we are creating a tuple 'tup' which contains string elements. Then we are retrieving the number of string elements of this tuple using the len() method.

# Creating the tuple
tup = ("Welcome", "To", "Tutorials", "Point")
# using len() method
result = len(tup)
#printing the result
print('The length of the tuple is', result)

While executing the above code we get the following output −

The length of the tuple is 4

Example

In here, we are creating an empty tuple 'tup'. Then the length of this tuple is returned using the len() method.

# Creating an empty tuple
tup = ()
# using len() method
result = len(tup)
#printing the result
print('The length of the tuple is', result)

Following is an output of the above code −

The length of the tuple is 0

Example

In the following example we are creating a nested tuple 'tup'. Then we retrieve the length of the tuple usin len() method. To retrieve the length of the nested tuple we are using nested indexing with the index'0'.

# creating a nested tuple
tup = (('1', '2', '3'), ('a', 'b', 'c'),('1a', '2b', '3c'), '123', 'abc')
result = len(tup)
print('The length of the tuple is: ', result)
# printing the length of the nested tuple
nested_result = len(tup[0])
print('The length of the nested tuple is:', nested_result)

Output of the above code is as follows −

The length of the tuple is:  5
The length of the nested tuple is: 3
python_tuples.htm
Advertisements