Lesson 7 of 8 · 34 min · Grades 6–8
Lists — several items in one bag
A shopping list is one scrap of paper with many lines: milk, bread, mangoes. You do not invent a new variable milk1, milk2. A Python list is square brackets with items separated by commas. You can walk through the list with a for loop — “for each item, buy it”.
Market shopping list
A list holds many items together.
You will be able to
- ✓ Create a list and print it
- ✓ Loop through each item
- ✓ Use len() and append()
A list is an ordered collection
bag = ["milk", "bread", "mango"] holds three strings in order. The order is part of the data: first item is what you buy first if you walk the market aisle by aisle.
Lists can hold numbers too: scores = [70, 88, 91]. Mixed types are legal in Python but confusing; keep one kind per list when you are learning.
Index starts at 0
The first item is bag[0], the second bag[1]. It feels odd because humans say “first” as 1. Computers say 0. This matches range: the first turn of range(3) is also 0.
Asking for bag[9] when there are three items is an error in real Python. Count with len(bag) before you assume an index exists.
append grows the list
If Amma remembers eggs at the gate, bag.append("eggs") adds at the end. You do not rewrite the whole list. len(bag) then reports the new length.
for item in bag: visits each element in order. You almost never write for i in range(len(bag)) at this level — looping the items directly is clearer.
Words that matter
- List
- An ordered collection in square brackets.
- Index
- The position of an item, starting at 0.
- append
- A method that adds one item at the end.
Common mistakes
Avoid: Using bag(0) with round brackets.
Do this: Indexing uses square brackets: bag[0].
Avoid: Expecting the first item at [1].
Do this: The first item is [0].
Example program — Sunday market bag
Add one more fruit with append and Run. Count should rise.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Sports day kit
Make a list that includes shoes. Loop and print each item. Output must contain shoes.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.