Python len() Function
Last Updated :
02 Aug, 2022
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:
Python3
list1 = [ 'geeks' , 'for' , 'geeks' , 2022 ]
print ( len (list1))
tuple1 = ( 1 , 2 , 3 , 4 )
print ( len (tuple1))
string1 = "geeksforgeeks"
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.
Python3
num = 10
print ( len (num))
d = 9.9
print ( len (d))
boolean = True
print ( len (boolean))
c = 7 + 8j
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.
Please Login to comment...