Skip to main content

Example: Printing Elements in a List

Sequencing principles demonstrated

A variation (a problem solving sequence)

Prerequisite content

Prior to asking the learner to solve a problem, the following content is provided.

Working with lists

A list stores multiple elements of the same type. The following code shows some common operations that can be done on lists.

Define a list with 5 elements

list = [14, 63, 26, 88, 72]

The first element is at position 0 of the list.

print(list[0])
# The second element is at position 1 of the list.
print(list[1])

Expressions inside list brackets

# When using brackes to retrieve an element in the list, the code in between in the brackets
# is an expression that evaluates to an integer value. This is shown below, where
# the expression is [position + 1]
position = 2

print(list[position + 1]) # Print the fourth element of the list. The fourth element is at position 3 of the list.
print(len(list))

Using loops for counting

for i in range(5): # Count from 0 to 4
print(i)
for i in range(5):
print(i + 1)

Again print the numbers from 1 to 5

# Like the input to the print function,
# the input to the range function is an expression.
# Here, the input expression to range evaluates to 5

n = 2
for i in range(3 + n)
print(i + 1)

Problem

Suppose you have a list list. Display each item in list.

Sequencing

To make this problem easier to solve, the following code can be provided. This problem is a variation with our without the code below.

for i in range(<code here>):
print(<code here>)

Solution

for i in range(len(list)):
print(list[i]) # Print the element at the position

This a variation of the loops that are demonstrated in the Using loops for counting section. The loop operates on a list instead of numbers.