Python Practice › Loop Programs › Program 79

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.

Advertisement
Input
["s", "q", "a", "t", "o", "o", "l", "s"]
Output
s | shortcut: s

Approach

  1. 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])
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.

More loop programs

← All 90 Loop Programs

Leave a Comment