Store an ordered collection of values in a list, read items by position, and check length and membership.
About 30 minBeginner4 exercisesFree
You will be able to
Create lists of numbers and strings, including an empty list
Read items by position with positive and negative indexes
Use len() and the in operator to answer questions about a list
Loop over a list and explain why an IndexError happens
Imagine a café that records the price of every order today. With one variable per order — order1, order2, order3 — you couldn't even write the program until you knew how many orders there would be. What you need is one name for the whole collection.
A list is exactly that: an ordered collection of values stored under a single name. You write it with square brackets and separate the items with commas:
A list can hold any type of value, it keeps the items in the order you gave them, and it can contain the same value more than once.
A list of today's order totals
orders =[18.5,12.0,25.75,9.0,12.0]print(orders)print("Number of orders:",len(orders))print("Type:",type(orders))
Try it: Add another price to the end of the list and run it again. Watch len() change.
Indexing: reading one item
Each item has a position called its index. Python counts from 0, so the first item is at index 0, the second at index 1, and the last at index len(list) - 1. You read an item by putting its index in square brackets after the list's name.
Python also accepts negative indexes, which count from the end: -1 is the last item, -2 the one before it. They save you from writing orders[len(orders) - 1].
Item
"Huda"
"Omar"
"Rania"
Index
0
1
2
Negative index
-3
-2
-1
Positive and negative indexes
queue =["Huda","Omar","Rania","Sami"]print(queue[0])# first personprint(queue[2])# third personprint(queue[-1])# last personprint(queue[-2])# second from the end
last_position =len(queue)-1print(queue[last_position])
Try it: Print queue[1] and queue[-3]. Why are they the same person?
If you ask for a position past the end, Python stops with an IndexError. A list of 4 items has indexes 0 to 3 (or -1 to -4); index 4 does not exist. This is the most common list bug, usually from forgetting that counting starts at 0.
Try it: Fix the program so it prints the last person, using len(queue) - 1 or -1.
Membership and looping
The in operator asks "is this value somewhere in the list?" and gives True or False. not in asks the opposite. Comparisons are exact: "omar" is not in a list that contains "Omar".
A for loop visits the items in order, one per pass, as you saw in the loops track. You rarely need the index to process every item.
Checking a guest list and adding up a bill
guests =["Huda","Omar","Rania"]print("Omar"in guests)print("omar"in guests)print("Laila"notin guests)
bill =[18.5,12.0,25.75]
total =0for price in bill:
total = total + price
print("Total:", total)
Try it: Change the loop so it also counts how many prices are above 15.
Guided practice · ●difficulty 1 of 5 · about 4 min
First and last delivery
A courier's route is a list of stop names in the order they will be visited. Write a function first_and_last(stops) that returns a string describing the first and last stop, in this exact format:
You can assume the list has at least one stop. The starter code has the right shape, but it picks the wrong stops (and sometimes crashes); fix it.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Challenge · ●●difficulty 2 of 5 · about 6 min
Readings over the limit
A cold-storage room logs its temperature every hour. Write a function count_over(readings, limit) that returns how many readings are strictly greater than limit.
Examples:
count_over([3.5, 4.1, 6.2, 5.0, 7.8], 5.0) returns 2 (6.2 and 7.8; 5.0 is not over the limit)
count_over([], 4) returns 0
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Edge cases · ●●difficulty 2 of 5 · about 6 min
Look up a shelf safely
A warehouse app shows the product on shelf number position (counting from 0). Users sometimes type a shelf number that doesn't exist. Write a function item_at(shelves, position) that returns shelves[position] when that index exists, and the string "No such shelf" otherwise.
Accept negative positions the same way Python does (-1 is the last shelf), as long as they are valid.
item_at(["rice", "flour", "sugar"], 3) returns "No such shelf"
item_at([], 0) returns "No such shelf"
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Challenge · ●difficulty 1 of 5 · about 4 min
Check the attendance list
A trainer keeps a list of the people who attended today's session. Write a function attendance_message(present, name) that returns "<name> attended" if the name is in the list and "<name> was absent" otherwise. Names must match exactly, including capital letters.
attendance_message(["Dana", "Fares", "Reem"], "Majid") returns "Majid was absent"
Use the in operator rather than a loop.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Summary
A list is an ordered collection written with square brackets; it can be empty and can hold duplicates.
Indexes start at 0; negative indexes count from the end, so items[-1] is the last item.
len(items) gives the number of items; the last valid index is len(items) - 1.
value in items checks membership exactly; a for loop visits every item in order.