![]() |
VOOZH | about |
The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example:
13
Explanation: The string "GeeksforGeeks" has 13 characters. The len() function counts and returns this number.
len(object)
Parameter: object is a sequence (such as a string, list, tuple) or collection (such as a dictionary, set) whose length is to be calculated.
Returns: An integer value indicating the number of items in the object.
Example 1: In this example, we are getting the length of a list, tuple and dictionary and printing the result for each.
4 4 3
Explanation:
Example 2: In this example, we are getting the length of an empty list and printing the result.
0
Explanation: Since the list is empty, len() returns 0, indicating there are no elements inside it.
Example 3: In this example, we are using len() along with a for loop to access and print each element of a list by its index.
Index: 0 Value: 10 Index: 1 Value: 20 Index: 2 Value: 30 Index: 3 Value: 40 Index: 4 Value: 50
Explanation: In this example, range() and len() are used to iterate over the list a by index. len(a) gives the total number of elements and range(len(a)) provides the index sequence. In each iteration, a[i] accesses the value at index i.