The "len()" function can be used with many data types, such as strings, lists, tuples, and dictionaries. The function counts the number of elements in the object and returns the result as an integer.
Syntax: The syntax for the "len()" function is as follows:
|
len(object)
|
where:
Example 1:
|
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
|
In this example, we have created a list "my_list" with 5 elements. We then use the "len()" function to find the length of the list and print the result. The output of this code will be:
Output:
|
5
|
Example 2:
|
my_string = "Hello World"
print(len(my_string))
|
In this example, we have created a string "my_string" with 11 characters. We then use the "len()" function to find the length of the string and print the result. The output of this code will be:
Output:
|
11
|
|
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))
|
In this example, we have created a tuple "my_tuple" with 5 elements. We then use the "len()" function to find the length of the tuple and print the result. The output of this code will be:
Output:
|
5
|
|
my_dict = {"name": "John", "age": 25, "gender": "Male"}
print(len(my_dict))
|
In this example, we have created a dictionary "my_dict" with 3 key-value pairs. We then use the "len()" function to find the length of the dictionary and print the result. The output of this code will be:
Output:
|
3
|
In conclusion, the "len()" function is a very useful built-in function in Python that returns the length of an object. It can be used with many data types and is commonly used in many Python programs to find the length of strings, lists, tuples, and dictionaries.