How to Use len() Function in Python: Syntax and Examples
In Python, use the
len() function to get the number of items in a collection like a string, list, or tuple. Just pass the collection inside the parentheses, for example, len(my_list) returns the count of elements in my_list.Syntax
The len() function takes one argument, which is the collection you want to measure. It returns an integer representing the number of items in that collection.
- len(s): where
sis a string, list, tuple, dictionary, or other collection. - The function counts elements, characters, or keys depending on the type.
python
len(s)Example
This example shows how to use len() with different types: a string, a list, and a dictionary.
python
my_string = "hello" my_list = [10, 20, 30, 40] my_dict = {"a": 1, "b": 2, "c": 3} print(len(my_string)) # Counts characters print(len(my_list)) # Counts list items print(len(my_dict)) # Counts dictionary keys
Output
5
4
3
Common Pitfalls
Some common mistakes when using len() include:
- Passing a number instead of a collection causes an error.
- Expecting
len()to count nested items inside collections (it only counts top-level items). - Using
len()onNoneor unsupported types raises an error.
python
wrong_value = 123 # print(len(wrong_value)) # This will cause a TypeError correct_value = [1, 2, 3] print(len(correct_value)) # Correct usage, outputs 3
Output
3
Quick Reference
| Usage | Description | Example |
|---|---|---|
| len(s) | Returns number of items in collection s | len([1,2,3]) → 3 |
| len('text') | Returns number of characters in string | len('hello') → 5 |
| len(dict) | Returns number of keys in dictionary | len({'a':1,'b':2}) → 2 |
Key Takeaways
Use len() to find the number of items in strings, lists, tuples, dictionaries, and other collections.
Pass only collections or sequences to len(); passing numbers or None causes errors.
len() counts top-level elements, not nested items inside collections.
The function returns an integer representing the count.
Remember len() works on many built-in types, making it very versatile.