liveBook · Manning

Len()

As explained in Get Programming: Learn to code with Python

len is a Python built-in function that returns the number of items in an object, including the number of characters in a string.

len() returns how many items an object contains. For a string, it counts every character between the quotation marks, including spaces and symbols; an empty string has length 0. section 7.3

Use len() with several common sequence objects:

  • len("Boston 4 ever") evaluates to 13, while len("") evaluates to 0. section 7.3
  • len((3, 5, "7", "9")) evaluates to 4 because the tuple contains four objects. section 10.2
  • len(grocery) returns 3 for a grocery list containing milk, eggs, and bread; an empty list has length 0. section 25.2

Counting a grocery list

grocery = ["milk", "eggs", "bread"] print(len(grocery)) The program prints 3. The first element is at index 0, and the last element is at index len(grocery) - 1, or index 2. section 25.2

Quick checks:

  • Predict the results of len(("hi", "hello", "hey", "hi")), len(("abc", (1, 2, 3))), len(((1, 2),)), and len(()). section 10.2
  • Use len() before indexing a list so you can recognize when an index is beyond the list's limits and causes IndexError. section 25.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines len() with worked string, tuple, and list examples, then connects list length to indexing limits.
Examples
Uses an essay character limit, sample strings, nested tuples, grocery lists, and tuple-length quick checks.
What it assumes
Assumes familiarity with strings, tuples, lists, variables, and zero-based indexing.
What you can do after
Apply it to calculate sequence sizes and identify valid list index positions.
How it connects
Connects len() to strings, tuples, lists, sequences, indexing, and IndexError.

Also explained in

Compare how 3 books explain len() →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.