
Python len() Function Explained
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.
Syntax of len() Function
len(value)
Python len() Function Parameters
- value: The object (string, list, tuple, dictionary, etc.) whose length you want to determine.
Return Value
- The function returns an integer representing the number of elements in the given object.
Python len() Function with Different Data Types
1. Finding the Length of a String
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.
2. Finding the Length of a List
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.
3. Finding the Length of a Tuple
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.
4. Finding the Length of a Dictionary
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.
5. Finding the Length of an Array
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().
Special Cases in len() Function
- 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
- None Value Throws an Error:
print(len(None)) # Raises TypeError
Summary
- 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.