inspection
len (built-in)
Returns the number of elements in the list as an int. O(1) because CPython lists track their length internally.
len(list) Parameters
| Parameter | Purpose |
|---|---|
| (one positional) | Takes exactly the list (or any Sized object). |
| empty check | Prefer `if lst:` over `if len(lst) > 0:` — more Pythonic and equally correct. |
Examples
>>> len([1, 2, 3])
3 Basic length.
>>> len([])
0 Empty list has length 0.
>>> len([[1, 2], [3]])
2 Counts top-level elements — does not recurse.
>>> lst = [1, 2]
>>> if lst: print('non-empty')
non-empty Truthiness check avoids explicit len().
Gotcha
len() counts only top-level elements — for nested totals, use sum(len(x) for x in nested). Prefer `if lst:` over `if len(lst) > 0:`.
Related methods
list.count
Returns the number of times x appears in the list. Comparison uses equality; returns 0 if x is not present (never raises).
x in list
Membership test operator that returns True if any element equals x, else False. Runs in O(n) — for repeated lookups, convert to a set (O(1) per test).
list.clear
Removes all items from the list in place. Equivalent to `del lst[:]`; returns None.
← All Python list methods · Dict methods · list vs tuple vs set