liveBook · Manning

Len()

As explained in A Pythonic Adventure: From Python basics to a working web app

The Python len function returns the number of items in a container or characters in a string.

Need a menu divider that always matches its title? Use len(). It returns the number of characters in a string or items in a container. section 3.0

Try it in the REPL

Type len('abcd') to get 4. It also works through variables: len('hello') gives 5, and len([1, 2, 3]) gives 3. Combine it with string repetition: len('hello') * '-' produces '-----'. section 3.0

In a menu function, print(len(title) * '-') so the divider grows or shrinks with the title instead of requiring manual counting. section 3.0

Listing 3.1 The full menu program with a function
def menu(choices, title="Erik's Menu", prompt="Choose your item: "):
    print(title)
    print(len(title) * "-")
    i = 1
    for c in choices:
        print(i, c)
        i = i + 1
    choice = input(prompt)
    answer = choices[int(choice) - 1]
 
    return answer
 
 
drinks = ["chocolate", "coffee", "decaf"]
flavors = ["caramel", "vanilla", "peppermint", "raspberry", "plain"]
toppings = ["chocolate", "cinnamon", "caramel"]
 
drink = menu(drinks)
flavor = menu(flavors, "Erik's flavors", "Choose your flavor: ")
topping = menu(toppings, "Erik's toppings", "Choose your topping: ")
 
print("Here is your order: ")
print("Main product: ", drink)
print("Flavor: ", flavor)
print("Topping: ", topping)
print("Thanks for your order!")

See the complete coffee-shop menu program using len() alongside function parameters, loops, lists, input, and return values. section 3.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Defines len() through interactive string and list examples, then applies it in a function without covering implementation internals.
Examples
Demonstrates len('abcd'), len('hello'), len([1, 2, 3]), and a title-sized divider in a coffee-shop menu.
What it assumes
Assumes basic Python expressions, strings, lists, and function calls while demonstrating len() from simple examples.
What you can do after
Apply it via Python to measure strings or lists and generate automatically sized menu dividers.
How it connects
Connects len() with strings, lists, string repetition, functions, loops, and the Python REPL.

Also explained in

Compare how 3 books explain len() →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.