Skip to main content

Section 9.5 Length

The len function, when applied to a string, returns the number of characters in a string.
To get the last letter of a string, you might be tempted to try something like this:
That won’t work. It causes the runtime error IndexError: string index out of range. The reason is that there is no letter at index position 6 in "Banana". Since we started counting at zero, the six indexes are numbered 0 to 5. To get the last character, we have to subtract 1 from the length. Give it a try in the example above.
Alternatively, in Python we can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on. Try it!
Typically, a Python programmer would combine lines 2 and 3 from the above example into a single line:
last_ch = fruit[len(fruit)-1]
You can use the len function to access other predictable indices, like the middle character of a string.:
fruit = "grape"
mid_char = fruit[len(fruit)//2]
# the value of mid_char is "a"
As with strings, the function len returns the length of a list (the number of items in the list). However, since lists can have items which are themselves sequences (e.g., strings), it is important to note that len only returns the top-most length.
Note that alist[0] is the string "hello", which has length 5.
Check your understanding

Checkpoint 9.5.1.

    What is printed by the following statements?
    s = "python rocks"
    print(len(s))
    
  • 11
  • The blank space counts as a character.
  • 12
  • Yes, there are 12 characters in the string.

Checkpoint 9.5.2.

    What is printed by the following statements?
    alist = [3, 67, "cat", 3.14, False]
    print(len(alist))
    
  • 4
  • len returns the actual number of items in the list, not the maximum index value.
  • 5
  • Yes, there are 5 items in this list.

Checkpoint 9.5.3.

Assign the number of elements in lst to the variable output.
You have attempted of activities on this page.