AppDividend
Latest Code Tutorials

Python Len Example | Python Inbuilt len() Function

1

Python len() is an inbuilt function that returns the length of any iterable objects. It returns the no. of characters of String; it returns the total number of items of list or dictionary. You can use the len() function to any iterable objects. It returns an integer which is the length of that iterable object.

Python len Example

The syntax of the Python len function is the following.

len(any iterable object)

An only required argument is an iterable object which can be a list, string or dictionary.

Calculate Length of String in Python

We can calculate the length of the String using the following code.

# app.py

strA = 'AppDividend'
print(len(strA))

See the output.

Python Len Built-In Function Tutorial With Example

The output is 11 which means that String AppDividend contains the 11 characters.

Calculate length of List in Python

We can calculate the length of the List. Calculating the length of the list means that we need to count the number of items the list has.

See the following code.

# app.py

listA = ['PlayStation', 'Xbox', 'PSP', 'Wii']
print(len(listA))

See the output.

Calculate List Length in Python

Calculate length of Dictionary in Python

We can also use Python len() function to calculate the length of the Dictionary in Python.

See the below code.

# app.py

dictA = {
    'name': 'Krunal Lathiya',
    'university': 'GTU',
    'enrollmentno': 110470116021,
    'college': 'VVP Engineering College'
}
print(len(dictA))

See the below output.

Calculate Length of Dictionary in Python

Use len() function in For loop

We can use the len() function in For loop. Let’s see the below example.

# app.py

ben10 = ['Jetray', 'EchoEcho', 'AlienX','DiamondHead', 'SwampFire']
i = 0
for i in range(0, len(ben10)):
    print(ben10[i])

In the above code, we have defined one list and then iterate that list from 0 to the length of the list. Then we have printed the alien one by one.

See the below output.

Use len() function in For loop

Finally, Python Len Built-In Function Tutorial With Example is over.

1 Comment
  1. Amit Parmar says

    Thanks for the post

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.