Open In App

Python len() Function

Python len() function is an inbuilt function in Python. It can be used to find the length of an object. 

Python len() function Syntax:

len(Object)



Parameter:

  • Object: Object of which we have to find the length for example string, list, etc.

Returns: It returns the integer value which indicates the length of an object.



For example, we can find the total number of characters in a string using the Python len() Function. It can be used with different types of data types except some of them.

Example:

Input: "geeksforgeeks"
Output: 13
Explanation: The input string contains 13 characters so output is 13.

Find the length of built-in Sequences

A container having ordered objects is called a sequence. Python has three fundamental built-in sequences: lists, tuples, and strings. We can find the length of these objects by using Python len() Function. Let’s take some examples:

Code:




list1 = ['geeks','for','geeks',2022]
# printing length of list1
print(len(list1))
 
tuple1 = (1,2,3,4)
# printing length of tuple1
print(len(tuple1))
 
string1 = "geeksforgeeks"
# printing length of string1
print(len(string1))

Output:

4
4
13

Examining other built-in data types with len()

Not all built-in data types can be used as arguments for len(). The concept of length is irrelevant for data types that only store a single object. The same is true for Boolean types and numbers. Let’s take some examples to understand it.




num = 10
# Printing length of num
print(len(num))
 
d = 9.9
# Printing length of float number 'd'
print(len(d))
 
boolean = True
# Printing length of boolean
print(len(boolean))
 
c = 7 + 8j
# Printing length of complex number 'c'
print(len(complex1))

Output:

Traceback (most recent call last):
  File "/home/9f7b2a9d90c3912d0e6fd0e4825f42fd.py", line 3, in <module>
    print(len(num))
TypeError: object of type 'int' has no len()

Traceback (most recent call last):
  File "/home/3f0127a097b085c2d840a24761d240cd.py", line 7, in <module>
    print(len(d))
TypeError: object of type 'float' has no len()

Traceback (most recent call last):
  File "/home/f1ca2dfd7b853e17f9abb93b1e822cd6.py", line 11, in <module>
    print(len(boolean))
TypeError: object of type 'bool' has no len()

Traceback (most recent call last):
  File "/home/b5a486420afaeff59dc5dbb7f4341ab3.py", line 15, in <module>
    print(len(complex1))
NameError: name 'complex1' is not defined

As we can see in the above output if we are trying to print the length of built-in data types such as int, float, and bool using Python len() function it gives an error.


Article Tags :