Python len() Function: Get Length of Objects | Syntax, Examples and Use Cases

Introduction: Python len() Built-in Function

When working with data in Python, it is often necessary to know how many elements an object contains. The Python len() function provides a simple and efficient way to determine the size of a collection or sequence.

What it is: It is a built-in Python function, meaning it is always available for use without importing any module. It returns the number of items stored inside an object. The result depends on the type of object—for example, characters in a string, elements in a list or tuple, or key-value pairs in a dictionary.

This function is widely used in everyday programming tasks such as validating input, checking whether collections are empty, and controlling loops that process data. Because it works with many built-in data structures, it becomes one of the most frequently used and essential functions in Python programs.

With this basic understanding, let’s explore the syntax, parameters, return value of the len() function before exploring examples and use cases.

Python len() Function: Syntax, Parameters, Return Value & Examples

Before using the function in real programs, it helps to understand how the len() function is written and what type of values it accepts. The structure is very simple, which makes the function easy to learn and apply.

Syntax

The syntax is straightforward. You only need to pass the object whose length you want to measure.

len(s)

Here, s represents the object whose size needs to be calculated. Python evaluates the object and returns the number of elements it contains.

Parameters

The function accepts only one parameter. This parameter can be any sequence or collection that supports length calculation.

Parameter Type Description
s Sequence or collection Any object that supports length calculation, such as a string, list, tuple, dictionary, set, or range.

Internally, Python determines the result by calling the object’s built-in __len__() method.

Return Value

Understanding what the function returns helps when using it inside conditions or loops.

  • The len() function returns the number of elements contained in an object.
  • The returned value is always an integer.
  • The function does not modify the original object; it only reports its size.
  • It is commonly used to validate input, check empty collections, or control iterations in loops.

Quick Example

The following example shows how the function returns the length of a string.


text = "Python"
print(len(text))


#Output:
6

The function counts each character in the string and returns the total number of characters.

How the Python len() Function Works

Although the function appears simple, its behavior depends on the type of object provided. In each case, the len() function counts the items that belong to that structure.

Although the function appears simple, its behavior depends on the type of object provided. The following breakdown shows how the len() function works with different data structures:

  • Returns an integer representing the number of items present in the object.
  • strings → counts characters
  • lists, tuples, and sets → counts elements
  • dictionaries → counts key-value pairs

Examples of Python len() Function for Different Data Types

The following examples demonstrate how the len() function behaves with different Python data types. Each example highlights how the function counts elements based on the structure of the object.

Example 1: String – Finding Length

This example shows how the function counts the number of characters in a string.


text = "Python"
print(len(text))

#Output
6

The function counts each character in the string, including letters and spaces (if any) and returns the total number of characters.

Example 2: List – Counting Elements

Lists can store multiple elements and the function counts each element present in the list.


numbers = [10, 20, 30, 40]
print(len(numbers))

#Output
4

The list contains four elements, so the function returns 4.

Example 3: Tuple – Measuring Size

Tuples are similar to lists but are immutable. The function counts the number of elements in the tuple.


items = ('a', 'b', 'c')
print(len(items))

#Output
3

Each element in the tuple is counted, resulting in a total of three items.

Example 4: Set – Counting Unique Elements

Sets store only unique elements. Duplicate values are automatically removed before counting.


unique_numbers = {1, 2, 2, 3, 4}
print(len(unique_numbers))

#Output
4

Although duplicates are provided, the set keeps only unique values, so the total count is four.

Example 5: Dictionary – Counting Key-Value Pairs

For dictionaries, the function counts the number of key-value pairs.


person = {"name": "Alice", "age": 25, "city": "Delhi"}
print(len(person))

#Output
3

The dictionary contains three keys, so the function returns 3.

Example 6: Range – Calculating Length

The function counts how many numbers are generated in the range sequence.


r = range(1, 6)
print(len(r))

#Output
5

The range generates five numbers (1 to 5), so the function returns 5.

Example 7: Bytes – Counting Bytes

The function counts the number of bytes in a bytes object.


data = b"ABC"
print(len(data))

#Output
3

Each character represents one byte, so the total length is three.

Example 8: Nested List – Finding Length

For nested structures, the function counts only the top-level elements.


nested = [1, 2, [3, 4], 5]
print(len(nested))

#Output
4

The inner list is treated as a single element, so the total count is four.

Use cases of Python len() Function

The len() function is widely used in real-world Python programs to measure the size of data and control program flow. Some common use cases include:

  • Input validation → Ensuring usernames, passwords, or text inputs meet length requirements
  • Loop control → Iterating through elements using length-based conditions
  • Checking empty collections → Verifying whether a list, string, or dictionary is empty
  • Data processing → Counting elements before performing operations
  • Conditional logic → Making decisions based on the size of data

Key Examples at a Glance: Python len() Function

The table below summarizes how the len() function behaves across different data types using the same examples demonstrated earlier.

Example Object Type Code Result
Example 1 String len("Python") 6
Example 2 List len([10, 20, 30, 40]) 4
Example 3 Tuple len(('a', 'b', 'c')) 3
Example 4 Set len({1, 2, 2, 3, 4}) 4
Example 5 Dictionary len({"name": "Alice", "age": 25, "city": "Delhi"}) 3
Example 6 Range len(range(1, 6)) 5
Example 7 Bytes len(b"ABC") 3
Example 8 Nested List len([1, 2, [3, 4], 5]) 4
Example 9 Custom Object len(MyData([10, 20, 30, 40])) 4

Key Takeaways: Python len() Function

Here are the most important points to remember about the len() function:

  • len() is a built-in Python function used to find the size of an object.
  • It returns the number of elements in a collection or sequence.
  • The return value is always an integer.
  • It works with multiple data types such as strings, lists, tuples, sets, dictionaries, and more.
  • For dictionaries, it counts key-value pairs, not individual values.
  • Custom objects can also use len() if they define the __len__() method.
  • The function does not modify the original object.
  • It is commonly used for validation, loops, and conditional checks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top