sodcalculator

10 Tech How-To

Python List Length: How to Count Items

Guide 10-46403 · Updated · Step by step

This guide shows you how to get the number of items in a Python list using the built-in len() function, plus a few alternatives. You’ll learn the correct syntax, see examples, and avoid common pitfalls. No special libraries are needed—just a working Python environment (Python 3 recommended).

What You’ll Need

  • Python 3.x installed on your computer (or an online Python interpreter).
  • A text editor or IDE (like VS Code, PyCharm, or IDLE).
  • Basic familiarity with Python lists (how to create and access them).

Step-by-Step

  1. Create a list (if you don’t have one already). For example: my_list = [10, 20, 30, 40] or fruits = ['apple', 'banana', 'cherry'].
  2. Use the len() function. Type len(my_list) and it will return the number of elements. For the examples above, len(my_list) gives 4, and len(fruits) gives 3.
  3. Store the result in a variable if needed. Example: count = len(my_list). Then you can use count in your code.
  4. Print the result. Use print(len(my_list)) to see the number directly in the console.
  5. Handle empty lists. If the list is empty, len() returns 0. This is often used to check if a list has any items: if len(my_list) == 0:.
  6. Count items in a list of lists (nested lists). len() only counts the top-level elements. For matrix = [[1,2], [3,4], [5,6]], len(matrix) returns 3, not 6. To count all inner items, you’d need a loop or a comprehension: sum(len(sub) for sub in matrix) gives 6.

Common Mistakes

  • Using len on a non-list. len() works on strings, tuples, dictionaries, and sets too, but if you pass an integer or a float, you’ll get a TypeError.
  • Forgetting parentheses. len my_list is invalid; you must write len(my_list).
  • Counting nested items incorrectly. As mentioned, len() doesn’t flatten nested lists. If you need the total number of elements in a nested structure, you must iterate.
  • Assuming len() starts at 1. It returns the actual count, not an index. For a list with 5 items, len() returns 5, but the last index is 4.

Tips

  • Use len() in loops. To iterate over a list by index, you can do for i in range(len(my_list)):.
  • Check for empty lists with if not my_list: This is more Pythonic than if len(my_list) == 0:.
  • For large lists, len() is O(1). It doesn’t count elements each time; it retrieves a stored value, so it’s very fast.
  • Combine with other functions. For example, len(my_list) - 1 gives the last index, useful for accessing the final element.

Troubleshooting

Problem: I get a TypeError: object of type 'int' has no len().
This means you passed a number instead of a list. Check that the variable you’re using is actually a list. You can verify with type(my_var).

Problem: len() returns a number that seems too high or too low.
Double-check that your list doesn’t have extra commas or missing elements. For example, [1,2,3,] has 3 elements, not 4. Also ensure you’re not accidentally counting a string as a list—len('hello') returns 5, not 1.

Problem: I need to count only certain items (e.g., numbers greater than 10).
len() counts all items. To count filtered items, use a comprehension: sum(1 for x in my_list if x > 10).

Problem: My list is a generator, not a list.
Generators don’t have a length. Convert it to a list first: my_list = list(my_generator), then use len().

Frequently Asked Questions

Can I use len() on a tuple or a dictionary?

Yes, len() works on any sequence or collection that has a defined length. For a dictionary, it returns the number of keys.

Does len() count duplicate items?

Yes, it counts every element, including duplicates. If you have [1,1,2], len() returns 3.

How do I count the number of occurrences of a specific item?

Use the list’s count() method: my_list.count(item). For example, [1,2,2,3].count(2) returns 2.

What is the difference between len() and list.__len__()?

They are essentially the same. len() calls the __len__() method internally. You can call my_list.__len__() directly, but it’s not recommended; use len() for readability.

Can I get the length of a list without using len()?

Yes, you can use a loop: count = 0; for _ in my_list: count += 1. But it’s slower and unnecessary. Stick with len().

Why does len() return an integer?

Because the number of items is always a whole number. It’s useful for comparisons and arithmetic, like if len(my_list) > 5:.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →