Python len() Function - With examples ?

The len() function prints out the length of the string (equivalent to the number of characters). And this function is built into Python. The performance of the program can be optimized when you use the len() function in Python. Because the number of elements in the object is difficult to calculate so len() was born to help you know that.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.

In this context, we shall look into how to use the len() function of Python.


What is the syntax of the len() Function in Python ?

Here's the syntax of the len() method in Python:

$ len(iterable_object)
$ len(object)


len() function Parameter Values is:

object: may be a string, a list, … (Required)


Examples of using the len() Function

1. Let's take a look at the below function:

list = ["cat", "dog", "pig"]
x = len(list)
print(x)

It's Output is given below:

3


2. The basic len() function:

list = ["cat", "dog", "pig"]
# Apply len() function
x = len(list)
# Print out the result
print("Length =",x)

The Output is given below:

Length = 3


3. The len() function with a string:

string = "hello"
# Apply len() function
x = len(string)
# Print out the result
print("Length =",x)

It's Output is given below:

Length = 5


3. The len() function with a set:

s = {5, 6, 7, 8}
# Apply len() function
x = len(s)
# Print out the result
print("Length =",x)

It's Output:

Length = 4


[Need help in fixing Python function issues ? We can help you. ]

This article covers how to use the len() function in Python. In fact, the Python len() method is a built-in function that can be used to calculate the length of any iterable object. So, if you want to get the length of a string, list, dictionary, or another iterable object in Python, the len() method can be useful.

Related Posts