📏

Understanding Python's len() Function

Apr 24, 2025

Python len() Function

Overview

The len() function in Python is a built-in function used to get the number of items in an object. It is commonly used with:

  • Strings
  • Lists
  • Tuples
  • Dictionaries
  • Other iterable or container types

Returns: An integer value representing the length or number of elements in the object.

Syntax

len(object)
  • Parameter: object can be a sequence (e.g., string, list, tuple) or a collection (e.g., dictionary, set) whose length is to be calculated.
  • Returns: An integer value indicating the number of items.

Examples of Usage

Example 1: Length of Various Data Types

# 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:

  • For the list a, len(a) returns 4, indicating four items.
  • For the tuple b, len(b) returns 4, indicating four elements.
  • For the dictionary c, len(c) returns 3, counting the number of key-value pairs.

Example 2: Length of an Empty List

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

Explanation: As the list is empty, len() returns 0.

Example 3: Using len() with a Loop

list_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.

Additional Information

  • The 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.