---Advertisement---

Python len() Function: How to Find the Length of Strings, Lists, and More Best 2025

By Bhavani

Updated On:

---Advertisement---
Python len() Function

Python len() Function: The len() function in Python is a powerful built-in method used to determine the number of items present in a string, list, tuple, dictionary, or array. This function is essential for managing data structures effectively in Python programs.


len(value)

  • value: The object (string, list, tuple, dictionary, etc.) whose length you want to determine.
  • The function returns an integer representing the number of elements in the given object.

str1 = “Welcome to Software Moji Moji Python Tutorials”

print(“The length of the string is:”, len(str1))

Output:
The length of the string is: 50

✅ Includes characters, spaces, and special characters in the count.


list1 = [“Tim”, “Charlie”, “Tiffany”, “Robert”]

print(“The length of the list is:”, len(list1))

Output:
The length of the list is: 4

✅ Each element is counted as one unit.


Tup = (‘Jan’, ‘Feb’, ‘March’)

print(“The length of the tuple is:”, len(Tup))

Output:
The length of the tuple is: 3

✅ Useful for counting immutable sequences like tuples.


Dict = {‘Tim’: 18, ‘Charlie’: 12, ‘Tiffany’: 22, ‘Robert’: 25}

print(“The length of the dictionary is:”, len(Dict))

Output:
The length of the dictionary is: 4

✅ Each key-value pair is counted as one unit.


arr1 = [‘Tim’, ‘Charlie’, ‘Tiffany’, ‘Robert’]

print(“The length of the array is:”, len(arr1))

Output:
The length of the array is: 4

✅ Arrays behave similarly to lists when using len().


  1. Empty String or Collection:

empty_str = “”

print(“The length of the empty string is:”, len(empty_str))

Output:
The length of the empty string is: 0

  1. None Value Throws an Error:

print(len(None))  # Raises TypeError


  • The len() function is essential for calculating the number of elements in strings, lists, tuples, dictionaries, and arrays.
  • It efficiently handles empty values but throws an error when applied to None.
  • Using len() correctly optimizes performance and ensures accurate element counting in Python programming.

Python format() String Method 

Download Python

Leave a Comment

Index