Python len() Function: How to find length of the string
Python len() Function
len() is a built-in function in python. You can use the len() to get the length of the given string, array, list, tuple, dictionary, etc. You can use len function to optimize the performance of the program. The number of elements stored in the object is never calculated, so len helps provide the number of elements.
Syntax
len(value)
Parameters
Value: the given value you want the length of.
Return value
It will return an integer value i.e. the length of the given string, or array, or list or collections.
Various types of Return values:
Strings:
It returns the number of characters in a string, which includes punctuation, space, and all type of special characters. However, you should be very careful while using len of a Null variable.
Empty:
Empty is a second return call which has zero characters, but it is always None.
Collections:
The len built-in returns the number of elements in a collection.
TypeError:
Len function depends on the type of the variable passed to it. A Non-Type does not have any built-in support.
Dictionary:
For the dictionary, each pair is counted as one unit. However, values and keys are not independent.
Example 1: How find the length of the given string?
# testing len() str1 = "Welcome to Guru99 Python Tutorials" print("The length of the string is :", len(str1))
Output:
The length of the string is : 35
Example 2: How to find the length of the list in python?
# to find the length of the list list1 = ["Tim","Charlie","Tiffany","Robert"] print("The length of the list is", len(list1))
Output:
The length of the list is 4
Example 3: How to find the length of a tuple in python
# to find the length of the tuple Tup = ('Jan','feb','march') print("The length of the tuple is", len(Tup))
Output:
The length of the tuple is 3
Example 4: How to find the length of the dictionary in Python?
# to find the length of the Dictionary Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("The length of the Dictionary is", len(Dict))
Output:
The length of the Dictionary is 4
Example 5: How to find the length of the array in python
# to find the length of the array arr1 = ['Tim','Charlie','Tiffany','Robert'] print("The length of the Array is", len(arr1))
Output:
The length of the Array is 4
Summary
- len() is a built-in function in python. You can use the len() to get the length of the given string, array, list, tuple, dictionary, etc.
- Value: the given value you want the length of.
- Return value a return an integer value i.e. the length of the given string, or array, or list, or collections.