Apr 24, 2025
len() FunctionThe len() function in Python is a built-in function used to get the number of items in an object. It is commonly used with:
Returns: An integer value representing the length or number of elements in the object.
len(object)
object can be a sequence (e.g., string, list, tuple) or a collection (e.g., dictionary, set) whose length is to be calculated.# List
list_a = ['geeks', 'for', 'geeks', 2022]
print(len(list_a)) # Output: 4
# Tuple
tuple_b = (1, 2, 3, 4)
print(len(tuple_b)) # Output: 4
# Dictionary
dict_c = {"name": "Alice", "age": 30, "city": "New York"}
print(len(dict_c)) # Output: 3
Explanation:
a, len(a) returns 4, indicating four items.b, len(b) returns 4, indicating four elements.c, len(c) returns 3, counting the number of key-value pairs.empty_list = []
print(len(empty_list)) # Output: 0
Explanation: As the list is empty, len() returns 0.
len() with a Looplist_d = [10, 20, 30, 40, 50]
for i in range(len(list_d)):
print("Index:", i, "Value:", list_d[i])
Output:
Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Index: 3 Value: 40
Index: 4 Value: 50
Explanation:
Here, range(len(list_d)) generates a sequence of indices, and list_d[i] accesses the list values by index.
len() function is an essential part of Python's built-in functions and is frequently utilized in various programming scenarios, such as loops, conditional statements, and data structure manipulations.For more examples and in-depth explanations, refer to GeeksforGeeks article on Python len() function.