Library contents

Python List indexing and len

Read a roster entry by zero-based position after checking how many names are available.

A simple example

List indexing and len

  1. Start with A, B, C
  2. Do this Read the second element
  3. Result B
Counting A as the first element puts B next in the sequence.

Syntax

Python syntax
names[index]
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Read the second name on the pickup roster

A teacher calls children in their recorded pickup order. The office asks for the second name on the roster, so the teacher checks that the list contains at least two entries before reading it.

From the programnames = ["Asha", "Mira", "Sam"]
ResultMira
lesson.py
names = ["Asha", "Mira", "Sam"]
if len(names) >= 2:
    print(names[1])
Output
Mira

Index one identifies the second child.

Advertisements

Prepare the next workshop roster

A teacher reads a workshop roster in arrival order. Who or what occupies the second position? Count from the front of the list.

GivenMira · Ivo · Bea
Worked resultIvo

Work from the delivery round

A courier has three labelled stops in route order. Who or what occupies the second position? Count from the front of the list.

GivenPark · Mill · Pier
Worked resultMill

What to watch for

Negative indexes count from the end. Reject them separately when a position comes from a seat number.

Documentation for List indexing and len