Python len()
Function
The len() function in Python is used to get the number of items in an object. It works with many data types like strings, lists, tuples, dictionaries, and more.
Syntax
len(object)
Parameter:
object
– A sequence (like string, list, tuple) or a collection (like dictionary, set, etc.).
Returns:
- An integer representing the number of items in the object.
Example 1: Length of a String
text = "Hello, World!"
print(len(text))
13
Example 2: Length of a List
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
5
Example 3: Length of a Tuple
values = (10, 20, 30)
print(len(values))
3
Example 4: Length of a Dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
print(len(person))
3
Note: len()
returns the number of keys in the dictionary.
Supported Data Types
- String
- List
- Tuple
- Dictionary
- Set
- Range
- Custom classes with
__len__()
method
Use Case: Why is len()
Useful?
- Checking if a list is empty:
if len(my_list) == 0:
- Limiting input size in forms or APIs
- Looping through data and keeping count
Common Mistake
- Wrong:
len(5)
→ RaisesTypeError
becauseint
has no length
Interview Tip
len()
is often used in interview coding problems to control loops, check constraints, or validate data. Know which data types it works on!
Summary
len()
returns the number of items in an object- Works with sequences and collections
- Raises
TypeError
if used on unsupported types likeint
orfloat
Practice Problem
Ask the user to enter a sentence. Print how many characters it contains:
sentence = input("Enter a sentence: ")
print("Number of characters:", len(sentence))
Comments
Loading comments...