How To Find The Length In Python

In this tutorial, we will learn how to find the length of various data types in Python, such as strings, lists, tuples, and dictionaries. Finding the length of an object is a common task in programming and Python provides a built-in function called len() to achieve this.

Step 1: Finding the length of a string

We’ll start with a string. In Python, a string is a sequence of characters enclosed in single or double quotes. To find the length of a string, use the len() function, and pass the string as the argument.

Example:

Output:

The length of the string is: 13

Step 2: Finding the length of a list

A list in Python is an ordered collection of items enclosed in square brackets []. The len() function can also be used to find the length of a list.

Example:

Output:

The length of the list is: 5

Step 3: Finding the length of a tuple

A tuple in Python is similar to a list but immutable, i.e., once assigned, its elements cannot be changed. Tuples are enclosed in round brackets (). To find the length of a tuple, use the len() function, and pass the tuple as the argument.

Example:

Output:

The length of the tuple is: 5

Step 4: Finding the length of a dictionary

A dictionary in Python is an unordered collection of key-value pairs enclosed in curly braces {}. To find the length of a dictionary, use the len() function and pass the dictionary as the argument.

Example:

Output:

The length of the dictionary is: 4

Full code

Output:

The length of the string is: 13
The length of the list is: 5
The length of the tuple is: 5
The length of the dictionary is: 4

Conclusion

In this tutorial, we learned how to find the length of different data types in Python, such as strings, lists, tuples, and dictionaries, using the built-in len() function. This function is quite versatile and can be used with various iterable objects to simplify handling and processing them.