Python len() Function

The len() function in Python is used to find the length of a sequence such as list, tuple, string, bytes, range or a collection such as dictionary, set, frozenset.

Basically the function len() returns the number items available in an object. For example:

```mylist = [32, 3, 65, 76]
print("Length of list =", len(mylist))

mytuple = (42, 53, 6)
print("Length of tuple =", len(mytuple))

mystring = "codescracker"
print("Length of string =", len(mystring))

mybyte = b'codescracker'
print("Length of byte =", len(mybyte))

myrange = range(15)
print("Length of range =", len(myrange))

mydictionary = {"Name": "Maradona", "Country": "Argentina"}
print("Length of dictionary =", len(mydictionary))

myset = {32, 43, 54, 56, 76, 8}
print("Length of set =", len(myset))

myfrozenset = frozenset(mytuple)
print("Length of frozenset =", len(myfrozenset))```

The output produced by above Python program, demonstrating the len() function, will exactly be:

```Length of list = 4
Length of tuple = 3
Length of string = 12
Length of byte = 12
Length of range = 15
Length of dictionary = 2
Length of set = 6
Length of frozenset = 3```

Python len() Function Syntax

Syntax to use len() function in Python is:

`len(objectName)`

Python len() Function Example

The len() function uses most of the time when we work with list or string in Python. Here is an example:

```print("Enter elements for the list (\"stop\" to exit): ", end="")
mylist = []
while True:
val = input()
if val != "stop":
mylist.append(val)
else:
break

print("\nThe list is:")
for i in range(len(mylist)):
print(mylist[i], end=" ")
print()```

The output produced by above program with some inputs and "stop" at last, to stop receiving inputs, is shown in the snapshot given below:

See how important the len() function is. In above program, the list continue storing the elements entered by user, until user enters "stop". But while printing the elements of the list back on the screen, the len() function find the length of the list, to print all the elements of the list using loop.

This is just a simple program. There are a multiple uses of len() function. Here is another example, uses len() function while working with string in Python:

```print("Enter the String: ", end="")
str = input()
print("\nLength of String =", len(str))```

Sample run with user input codescracker as string is show in the snapshot given below:

The len() function can be used in many programs. But always remember, it is used only to find the length of an object.

Python Online Test

« Previous Function Next Function »

Liked this post? Share it!