Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

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

Edge Cases

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

Python

  1. Master Python Strings: Creation, Formatting, and Manipulation
  2. Java String length() Method: How to Get a String’s Size (Example)
  3. Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
  4. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  5. Mastering Java's split() Method: A Practical Guide with Code Examples
  6. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
  7. Master Python's String.find() Method: Syntax, Examples & Alternatives
  8. Understanding Python's Main Function: A Practical Guide to def main()
  9. Mastering Python’s enumerate(): Loop with Indices for Lists, Tuples, Strings, and Dictionaries
  10. Mastering Python Strings: Creation, Access, and Manipulation