Scripting

Python len() Function

Python len() Function

Introduction

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.

And we will guide you on how to use the len() function of Python as we did below. Hope you understand.

Example

list = ["cat", "dog", "pig"]

x = len(list)

print(x)

Output:

3

Definition

The len() function prints out the number of elements in the variable.

If it is a string, len() will return the number of characters of the string.

The syntax

len(object)

Parameter Values:

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

More examples

Example 1: The basic len() function

list = ["cat", "dog", "pig"]

# Apply len() function

x = len(list)

# Print out the result

print("Length =",x)

Output:

Length = 3

Example 2: The len() function with a string

string = "hello"

# Apply len() function

x = len(string)

# Print out the result

print("Length =",x)

Output:

Length = 5

Example 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)

Output:

Length = 4

Conclusion

We have guided you on how to use the len() function in Python.

Thanks for referring!

Similar Posts