Python’s len() Function

Learn Python @

Python’s len() function is a fundamental tool for obtaining the length of sequences such as strings, lists, tuples, and more. In this comprehensive guide, we’ll delve into the intricacies of len(), covering its syntax, applications, and practical examples to help you utilize it effectively in Python programming. The len() function is a versatile tool in Python for determining the length of sequences, whether they’re strings, lists, tuples, or other iterable objects.

Understanding len() Function:

The len() function in Python is used to determine the number of items in a sequence or collection. Its syntax is simple:

  • sequence: The sequence (string, list, tuple, etc.) whose length you want to determine.

Example 1: Basic Usage

Let’s start with a simple example:

my_string = "Hello, World!"
print(len(my_string))  # Output: 13

Here, we have a string "Hello, World!", and len() returns the number of characters in the string, which is 13.

Example 2: Working with Lists

You can also use len() with lists:

my_list = [1, 2, 3, 4, 5]
print(len(my_list))  # Output: 5

In this example, len() returns the number of elements in the list, which is 5.

Example 3: Handling Empty Sequences

len() gracefully handles empty sequences:

empty_list = []
print(len(empty_list))  # Output: 0

Here, an empty list results in a length of 0.

Example 4: Finding Length of Nested Sequences

You can find the length of nested sequences as well:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(len(nested_list))  # Output: 3

In this case, len() returns the number of nested lists within the main list, which is 3.

Example 5: Working with Tuples

len() can also be used with tuples:

my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))  # Output: 5

Similarly, for tuples, len() returns the number of elements in the tuple, which is 5 in this case.

Author: user