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
- Start with A, B, C
- Do this Read the second element
- Result B
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.pyRead 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.
names = ["Asha", "Mira", "Sam"]
if len(names) >= 2:
print(names[1])
Mira
Index one identifies the second child.
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.
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.
What to watch for
Negative indexes count from the end. Reject them separately when a position comes from a seat number.