Last element with a while loop
EasyLoop Programs · 79 of 90
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"]
Approach
- Move an index to the end of the list, then read that item.
Solution
Python
c = ["s", "q", "a", "t", "o", "o", "l", "s"]i = 0while i < len(c) - 1: i += 1print(c[i], "| shortcut:", c[-1])
Line by line
Lines 3-4The loop stops on the last valid index.
Line 5c[-1] is the normal way to read the last item.
Learn the concept
New to this topic? Read the lesson, then come back.
More loop programs
← All 90 Loop Programs