How to Find Length of List in Python: Simple Guide
To find the length of a list in Python, use the
len() function by passing the list as an argument. It returns the number of items in the list as an integer.Syntax
The syntax to find the length of a list uses the built-in len() function.
len(list_name): Returns the number of elements in the list calledlist_name.
python
len(list_name)Example
This example shows how to use len() to get the length of a list of fruits.
python
fruits = ['apple', 'banana', 'cherry'] length = len(fruits) print(length)
Output
3
Common Pitfalls
One common mistake is trying to use len without parentheses, which will not give the length but the function itself. Another is passing something that is not a list or iterable, which causes an error.
python
fruits = ['apple', 'banana', 'cherry'] # Wrong: missing parentheses print(len) # This prints the function object, not the length # Right: use parentheses print(len(fruits)) # Correctly prints 3 # Wrong: passing non-iterable # print(len(5)) # This will cause a TypeError
Output
<function len>
3
Quick Reference
Remember these points when finding list length:
- Use
len(your_list)to get the number of items. - The result is an integer representing the count.
- Works with other collections like strings, tuples, and dictionaries.
Key Takeaways
Use the built-in
len() function to find the length of a list.len() returns an integer count of items in the list.Always include parentheses when calling
len().Passing non-iterable types to
len() causes errors.len() works with other iterable types like strings and tuples.