Read Python Interview Questions and Answers for Beginners and Experienced

How to use Python len() function

len() function is one of the Python built-in functions. In this Python tutorial for beginners we will study about len() function, its syntax and study deep by taking some len() examples in Python.

 

Introduction to Python len function

len() function is used to get the length of the object.

 

len(object)

 

  • len() is function name used to get the length of the object and return integer number.
  • object could be String, tuple, set, dict etc.
  • len() function returns the value in numeric.

 

Example of Python len function

Let’s see functionality of len() function by taking some examples.

 

Example of len() with String


# Python len() function example
str1="abc"
print("length of",str1,"is :",len(str1))

 

Output

length of abc is : 3

 

  • In above example Str1 is String having value “abc”
  • when we apply len() function on String str1, it counts the characters in String str1 and display that count value.

 

Use of len function with list , tuple etc


# Python len() function example

tuple1=(1,2,3)

print("length of",tuple1,"is :",len(tuple1))

list1 =["learn","Python","online","tutorials","for","beginners"]
print("length of",list1,"is :",len(list1))

 

Output

length of (1, 2, 3) is : 3
length of ['learn', 'Python', 'online', 'tutorials', 'for', 'beginners'] is : 6

 

  • In above example, we have one tuple and one list.
  • when we apply len() function on tuple and list, it gives the count of elements inside Python tuple and Python list.

 

len() function give the count of elements in any object is built with. See, String was built with characters, so it gives the count of characters in String ( we saw above in example). Tuple and list are built with elements , so len() function returns the count of elements inside tuple and list.