Python len() Function
The Python len() function returns number of elements in an iterable. An iterable object can be any data structure like list, tuple, set, string and dictionary etc. The range() function can also be used to create an iterable.
Syntax
len(iterable)
Parameters
iterable |
Required. specify iterable like a list, tuple, set, string , dictionary, and range(), etc. to find out total number of elements in it. |
Example: length of list, tuple, set, string and range()
In the example below, len() function is used on different iterables to find out the number of elements in it.
MyList = [1, 2, 3, 4, 5] print(len(MyList)) MyTuple = ('Blue', 'Red', 'Green') print(len(MyTuple)) MySet = {'Marry', 'John', 'Sam'} print(len(MySet)) print() MyString = 'Hello World!' print(len(MyString)) MyRange = range(0, 5) print(len(MyRange))
The output of the above code will be:
5 3 3 12 5
Example: length of a dictionary
In the example below, len() function is used on dictionary to find out the number of key-value pairs in it.
Info = { 'name': 'John', 'age': 25, 'city': 'London' } print(len(Info)) print(len(Info.keys())) print(len(Info.values()))
The output of the above code will be:
3 3 3
❮ Python Built-in Functions