Python Practice › Loop Programs › Program 79
Last element with a while loop
Write a Python program to print the last element of a list using a while loop.
Input
["s", "q", "a", "t", "o", "o", "l", "s"]
Output
s | shortcut: s
Approach
- Move an index to the end of the list, then read that item.
Solution
c = ["s", "q", "a", "t", "o", "o", "l", "s"]i = 0while i < len(c) - 1: i += 1print(c[i], "| shortcut:", c[-1])Output
s | shortcut: s
Line by line
Lines 3-4
The loop stops on the last valid index.
Line 5
c[-1] is the normal way to read the last item.
Learn the concept
New to this topic? Read the lesson, then come back.