6.5 Length

From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period1 exercise1 graded test

README.md

6.5 Length

Read first in the book: 6.4 Disambiguating []: creation vs indexing.

The len function, when applied to a string, returns the number of characters in a string.

fruit = "Banana"
print(len(fruit))

To get the last letter of a string, you might be tempted to try something like this:

fruit = "Banana"
sz = len(fruit)
last = fruit[sz]       # ERROR!
print(last)

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.

fruit = "Banana"
sz = len(fruit)
lastch = fruit[sz-1]
print(lastch)

Typically, a Python programmer would combine lines 2 and 3 from the above example into a single line:


lastch = fruit[len(fruit)-1]

Though, from what you just learned about using negative indices, using fruit[-1] would be a more appropriate way to access the last index in a list.

You can still use the len function to access other predictable indices, like the middle character of a string.


fruit = "grape"
midchar = fruit[len(fruit)//2]
# the value of midchar 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 important to note that len only returns the top-most length.

alist =  ["hello", 2.0, 5]
print(len(alist))
print(len(alist[0]))

Note that alist[0] is the string "hello", which has length 5.

Check your understanding

Check your understanding: a multiple-choice question in the book.

Check your understanding: a multiple-choice question in the book.

Exercise 1

Assign the number of elements in lst to the variable output.

Open the 01 folder and edit main.py. Run Tests checks it.

For teachers

6.5 Length

Students read Foundations of Python Programming's “Length” in CS Room and work through its 1 Python coding exercise (1 graded).

  • Time: 1 class period
  • Tests: 1 in 1 graded exercise, set up for you when you import the lesson

Reading first

Exercises

FolderGradingTests
01Autograded1