Python len(): A Practical Guide to Measuring Object Lengths
In Python, len() is a built‑in function that returns the number of items in an object. Whether you’re working with strings, lists, tuples, dictionaries, or other collections, len() gives you a quick, efficient way to determine size without performing any costly iteration.
Syntax
len(value)
Parameter
value – The object whose length you want to measure.
Return Value
Returns an integer representing the number of elements in the supplied object.
Strings
For a string, len() counts every character—including spaces, punctuation, and special symbols. Be cautious when passing a None value, as it will raise a TypeError.
Collections
- Lists & Tuples – Counts the number of elements.
- Dictionaries – Counts key‑value pairs; keys and values are not separated.
- Sets & Frozensets – Counts unique items.
Edge Cases
- Empty objects –
len([])returns 0. - Unsupported types – Passing a non‑sized type (e.g.,
int) raisesTypeError.
Examples
1. String Length
# Example 1
str1 = "Welcome to Guru99 Python Tutorials"
print("The length of the string is:", len(str1))
Output: The length of the string is: 35
2. List Length
# Example 2
list1 = ["Tim", "Charlie", "Tiffany", "Robert"]
print("The length of the list is", len(list1))
Output: The length of the list is 4
3. Tuple Length
# Example 3
tup = ("Jan", "Feb", "March")
print("The length of the tuple is", len(tup))
Output: The length of the tuple is 3
4. Dictionary Length
# Example 4
dict_obj = {"Tim": 18, "Charlie": 12, "Tiffany": 22, "Robert": 25}
print("The length of the dictionary is", len(dict_obj))
Output: The length of the dictionary is 4
5. Array Length (List Equivalent)
# Example 5
arr = ["Tim", "Charlie", "Tiffany", "Robert"]
print("The length of the array is", len(arr))
Output: The length of the array is 4
Key Takeaways
len()is versatile and efficient for any sized object.- It returns an integer; zero indicates an empty object.
- Always validate the object type to avoid
TypeError.
Python
- Master Python Strings: Creation, Formatting, and Manipulation
- Java String length() Method: How to Get a String’s Size (Example)
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
- Master Python's String.find() Method: Syntax, Examples & Alternatives
- Understanding Python's Main Function: A Practical Guide to def main()
- Mastering Python’s enumerate(): Loop with Indices for Lists, Tuples, Strings, and Dictionaries
- Mastering Python Strings: Creation, Access, and Manipulation