len() Function in Python

Python len() Function

The len() function in Python is used to determine the length (number of items) of an object. It works with various types of objects, such as strings, lists, tuples, dictionaries, and sets. Here's the general syntax:

len(object)

The object parameter is the object whose length you want to find. The len() function returns an integer representing the number of items in the object.

Here are some examples:

Finding the length of a string:

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

Finding the length of a list:

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

Finding the length of a dictionary (number of key-value pairs):

my_dict = {'a': 1, 'b': 2, 'c': 3}
print(len(my_dict))  # Output: 3

Finding the length of a set (number of unique elements):

my_set = {1, 2, 3, 4, 5}
print(len(my_set))  # Output: 5

It's important to note that the len() function may not be defined for all types of objects, and it may behave differently depending on the object's implementation. However, it is widely used and supported for most built-in types in Python.