Saturday, December 28, 2024
Google search engine
HomeLanguagesPython Tuple – len() Method

Python Tuple – len() Method

While working with tuples many times we need to find the length of the tuple, and, instead of counting the number of elements with loops, we can also use Python len(). We will learn about the len() method used for tuples in Python.

Example:

Python3




Tuple =( 1, 0, 4, 2, 5, 6, 7, 5)
print(len(Tuple))


Output :

8

Python tuple len() Method Syntax

Syntax: len(object)

Parameters:

  • object: Any iterable like Tuple, List, etc.

Return type: the number of elements in the tuple.

Tuple len() in Python Examples 

Empty Tuple

Here we are declaring an empty tuple and printing its length in Python.

Python3




empty_tuple = ()
length = len(empty_tuple)
print(length) 


Output :

0

Tuple of Integers

Here we are finding the length of a particular tuple.

Python3




# Creating tuples
Tuple = (1, 3, 4, 2, 5, 6)
 
res = len(Tuple)
print('Length of Tuple is', res)


Output :

Length of Tuple is 6

Tuple of Strings

Here we are finding the number of elements of the tuple that constitutes string elements.

Python3




# Creating tuples
Tuple = ("Geeks", "For", "Geeks", "GeeksForGeeks")
 
res = len(Tuple)
print('Length of Tuple is', res)


Output :

Length of Tuple is 4

Get the Length of the Nested Tuple

In this example, we have used created a tuple that consists of multiple tuples.

Python3




# alphabets tuple
alphabets = (('G', 'F', 'G'), ('g', 'f', 'g'),
             ('g', 'F', 'g'), 'GfG', 'Gfg')
 
res = len(alphabets)
print('Length of Tuple is', res)
 
res_nested = len(alphabets[0])
print('Length of nested tuple is', res_nested)


Output :

Length of Tuple is 5
Length of nested tuple is 3

Tuple with Mixed DataTypes

In this example, we have used multiple types of data in the tuple.

Python3




mixed_tuple = ('apple', 3, True, 2.5)
length = len(mixed_tuple)
print(length)


Output :

4

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments