To find length of string in python we use built-in function len().
The len() is used to find the length of the Object it can be string, tuple, list, dictionary, and set.
The detail of this function is as below
len() in Python
len() is a predefined function that returns the number of elements in the collection as integer values
Syntax
len(collection)
collection must be of sequence type
Python len() Example
python string length
finding a string length using len() is very simple you have to just pass the string inside len(). That will return a number of elements in the string.
1 2 3 | str='Welcome to Ebhor.com'; length=len(str); print('Length of string ', length); |
1 | Length of string 20 |
len python: Example to find the length of tuple
As we find string length we can also find tuple length in python.
In the below example, two tuples tuple1 and tuple2 initialized and passed to len() to get tuples length.
1 2 3 4 5 | tuple1=[1,2,3,4,5,6,7]; tuple2=['Ram','Mohan','Sohan','Rita','Nita']; length=len(tuple1); print('Length of tuple1 ', length); print('Length of tuple2 ', len(tuple2)); |
1 2 | Length of tuple1 7 Length of tuple2 5 |
len python: Example to find length of list python
Below two list list1 and list2 initialized. To find the length of list len() is used.
1 2 3 4 5 | list1=[1,2,3,4,5,6,7,8,9,10]; list2=['Ram','Mohan','Sohan','Rita','Nita','Ramesh','Suresh']; length=len(list1); print('Length of list1 ', length); print('Length of list2 ', len(list2)); |
1 2 | Length of list1 10 Length of list2 7 |
len python: Example to find length of dictionary python
We initialized a dictionary and find its length as below
1 2 3 | dict1={'Name':'Ram','age':22,'City':'Mumbai'} length=len(dict1); print('Length of dict1: ', length); |
1 | Length of dict1: 3 |
len python: Example to find length of set python
Python set is initialized as below and len() is used to find its length.
1 2 3 | set1={'Ram','Mohan','Sohan','Rita','Nita','Ramesh','Suresh'}; length=len(set1); print('Length of set1: ', length); |
1 | Length of set1: 7 |
What does len do in python
len() is a predefined function in python that is used to find the number of elements in sequenced collection type.