Python Lists: pack a cart, keep your promises
Build and revise a small shopping cart, explain what changes and what stays shared, then solve a new last-match problem using the same model.
What you need before starting
- Read string and integer literals, variables, print(), and == comparisons.
- Recognize an if condition and an indented for loop; a short function primer is provided before practice.
- Use Python 3.11 or newer. All examples use only Python and its standard library.
A function wrapper is explained before the exercises. You can read and experiment without saving or signing in.
Before you start
Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 20 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
Code, notes and your place are saved explicitly. Local run results are not stored as certified scores.
1. What a list is
A list keeps several items together. It remembers their order, allows repeated items, and lets you add, remove, or change items.
Understand first
Use a list when several items belong together and their order matters: a shopping cart, a queue of tasks, or a series of daily temperatures. One variable can hold the collection, so you do not need a separate variable for every item.
Words you will see
- Item / element
- One entry in a list. These two words mean the same thing here.
- Index
- The number of an item's position. Python starts counting positions at 0. In our diagrams, a slot means one position in the list.
- Mutable
- Able to change after creation. You can add, remove, or replace items in the same list.
Read the brackets, commas, and quotes
In cart = ["bread", "milk", "bread"], the square brackets create the list. Commas separate its three items. Quotes make each product name a string: a piece of text. cart is the variable name we use to work with this list.
An empty list is written []. A one-item list is ["bread"]. The brackets belong to the list notation; they are not extra items. len(cart) gives the number of items, not the number of letters in their names.
Order and repeated items are part of the information
The first "bread" and the second "bread" are two entries, even though their text is equal. This cart has three items, not two. A list does not remove repeated values for you.
Ordered means items keep their positions unless an operation changes them. It does not mean automatically sorted. ["milk", "bread"] stays in that order. Keeping duplicates and order is important when each entry represents a separate request.
Changing an item is different from adding one
The positions in our three-item cart are 0, 1, and 2. cart[1] means the item in the second position. cart[1] = "oats" replaces the milk with oats. There are still three items, and the two breads stay where they were.
A list can also hold numbers, other lists, or a mixture of values. Python allows this, but our cart will deliberately hold only product-name strings. A consistent kind of item makes the cart rules easier to understand. You do not need to understand memory or copying yet; we will introduce them when sharing a list becomes relevant.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
cart = ["bread", "milk", "bread"]Create three entries in this exact order. The repeated bread is kept.
print(len(cart))Count the entries, then display 3. len calculates a value; print displays it.
cart[1] = "oats"Replace the second entry. The count stays 3 because this does not add or remove a position.
print(cart)Display ['bread', 'oats', 'bread']. Single quotes in the display still represent the same strings as double quotes in the code.
Connect the idea to our cart
You are packing breakfast for a neighbor. You need bread, milk, then another bread for a second household. A list keeps these three requests together without forgetting the order or the repeated bread.
Read the explanation and the worked steps first. Then predict, run, and change the example to test your understanding. You do not need to run code to understand the explanation. Diagrams and expected outputs describe the original example; actual output comes from your run.
Conceptual slots, not a memory or heap measurement
- 1Build
cart → [0: 'bread', 1: 'milk', 2: 'bread']
- 2Count
len(cart) → 3; both bread slots count.
- 3Replace
cart[1] = 'oats' → [0: 'bread', 1: 'oats', 2: 'bread']
Ctrl/Cmd + Enter runs your current code. Runs stay in your browser; Save stores a private copy on CareerPetal. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Compare with the original example's expected output
This is reference output for the original code, not a run of your edits.
3 ['bread', 'oats', 'bread']
Now make it behave differently.
Replace the first bread instead.
Try: Change cart[1] to cart[0].
Indexes start at zero; only the first slot changes.
Explain why this is a list rather than a set.
Try: Keep both bread entries and compare their positions.
A set represents unique membership, not this ordered, duplicate-preserving packing plan.
Position is not the same as value.
This is a conceptual model, not an instrumented CPython heap or a trace of your edited program. Use Run Python above to verify real behaviour.
cartlist object A- 0 or -3breadreference to a string
- 1 or -2milkreference to a string
- 2 or -1breadreference to a string
Three positions refer to three string values.
The display stops at seven items for readability, not because Python lists have that limit.Keep this idea: A list remembers position, permits duplicates, and lets you replace its slots.
Before you move on
For names = ["Ana", "Bo", "Ana"], what does names[0] = "Cy" change? How many items remain?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Only the first entry changes. The result is ["Cy", "Bo", "Ana"], and len(names) is still 3. Equal text at two positions does not make those positions one entry.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
When you need the details: methods, costs and alternatives
CPython lists are dynamic arrays of references. Spare capacity makes append amortized O(1), but one resize can copy O(n) references. The diagrams are models, not measured memory layouts. Choose deque for repeated front removal, dict for keyed lookup, set for uniqueness and tuple for a fixed sequence contract.
Reading the cost labels: n means the number of items; k means the selected items. O(1) means work that does not grow with the list length, while O(n) grows in proportion to it. Amortized O(1) means constant work per addition when averaged over a sequence of additions, even though one addition can be expensive. Space means extra storage, not the size of the original input. These describe growth, not measured milliseconds.
| Operation | When it helps | Time | Extra space | Watch out |
|---|---|---|---|---|
Cost modelcart = ['bread', 'milk'] | Read this before comparing operations. n is current list length, k is copied or added items, and m is an exclusions-list length. | The bounds below describe CPython's resizable array of references, not a timing guarantee for every Python implementation. Treat item equality, ordering, and key work as constant cost; user-defined comparisons may cost more. | Space means additional storage, including a returned list; it excludes existing item objects. CPython keeps spare capacity, but these examples do not measure capacity, addresses, or heap allocation. | Amortized bounds describe a sequence of operations, not a promise that every individual call is cheap. |
len(cart), cart[i], cart[i] = itemcart[0] = 'oats' | Count slots, read one existing slot, or replace its reference. | O(1) each in CPython under the stated model. | O(1) additional space. | Indexing or replacement outside the current bounds raises IndexError; assignment at len(cart) is not append. |
cart.append(item)cart.append('tea') | Add one object to the end. | Amortized O(1) in CPython; an individual resize may copy O(n) references. | Amortized O(1) added storage per append over a sequence; a resize can require O(n) additional allocation. | Returns None. Appending a list adds one nested item. |
cart.extend(items)cart.extend(['tea', 'oats']) | Append every item from an iterable. | Amortized O(k) for k added items; a resizing call can take O(n + k). Iterable production costs are additional. | O(k) growth over a sequence, with possible O(n + k) resize allocation. | Returns None. A string supplies characters, not one whole product. |
cart.insert(i, item)cart.insert(0, 'bread') | Insert before a position; later references shift right. | O(n) worst case, including front insertion; an end insertion avoids shifting but can resize. | One logical new slot; a resize can require O(n) additional allocation. | Returns None and shifts positions. Out-of-range positions are clipped rather than raising IndexError. |
cart.pop() / cart.pop(i)last_item = cart.pop() | Remove and return an item, using the last position by default. | End pop is amortized O(1) in CPython; shrink work can make an individual call O(n). Arbitrary-index pop is O(n) worst case due to shifting. | O(1) usual extra working storage; a resizing implementation may temporarily need O(n) allocation. | Empty or invalid-index pop raises IndexError; indexes change after removal. |
del cart[i]del cart[0] | Delete a slot when you do not need its value. | O(n) worst case for shifting or resizing; deleting near the front shifts the suffix. | O(1) usual working storage; a shrink may temporarily allocate O(n). | del is a statement, not an expression returning the updated cart; invalid indexes raise IndexError. |
cart.remove(item)cart.remove('milk') | Find and delete the first equal value. | O(n) worst case for search plus shifting. | O(1) usual working storage; a shrink may temporarily allocate O(n). | Returns None and raises ValueError when absent. It does not choose the last occurrence. |
cart.clear()cart.clear() | Remove all slots from this list object. | O(n) to release its item references, not O(1). | O(1) additional working space, excluding object finalizers. | Returns None. Aliases see the emptied list; cart = [] instead rebinds only that name. |
item in cart'milk' in cart | Search for at least one equal value. | O(n) worst-case comparisons; an early match can stop sooner. | O(1) extra space under the comparison model. | Membership says whether a value occurs, not how many times or at which last index. |
cart[a:b], cart[:], cart.copy()breakfast = cart[1:3] | Copy selected references into a new outer list. | O(k) for a k-item slice; O(n) for a full shallow copy. | O(k) result storage; a full copy uses O(n). | The stop is excluded; nested mutable item objects remain shared. |
cart.sort()cart.sort() | Stably reorder the existing list; equal-key items keep relative order. | O(n log n) worst case in CPython, with adaptive O(n) cases for already ordered runs. | Up to O(n) auxiliary storage in CPython, despite being in-place at the API level. | Returns None and changes the order seen by aliases. Not all mixed types can be ordered together. |
sorted(cart)receipt = sorted(cart) | Build a new, stably sorted list while leaving the source order alone. | O(n log n) worst case under the comparison model, including an O(n) copy. | O(n) for the returned list and up to O(n) sorting workspace. | The new list is still shallow; nested objects are not recursively copied. |
filter into a fresh listpacked = [item for item in cart if item not in unavailable] | Select ordered occurrences without deleting from the source. | O(n × m) worst-case comparisons with a list of m exclusions. With a prebuilt set of strings, expected O(n) membership work; building that set takes expected O(m), not zero time. | O(n) worst-case output storage; an optional membership set adds O(m). | Set membership is average-case, not guaranteed O(1) in the worst case; do not use a set as the ordered duplicate-preserving output. |
independent nested rowstrays = [[0] * c for _ in range(r)] | Create each mutable row separately. | O(r × c + r) to build r rows of c zeroes, including empty rows. | O(r × c + r) for the outer list, all row lists, and cell references. | [[0] * c] * r repeats one row reference. Printed equality does not prove independence. |
What changed in your mental model?
- Predict, then explain: if helper = cart and spare = cart[:], which names see helper.append('tea')? Which see spare[0] = 'oats'? Draw names, outer lists, and item references separately.
- Explain why the flat-string copy in add_to_cart protects the caller, but bad.copy() did not separate the nested tray rows. Name the mutable object each contract promises to isolate.
- Give a new example with two matching products separated by other items. Trace remove_last by index and show that exactly one occurrence disappears while the original cart survives.
- Choose a list, tuple, set, dict, or deque for a new packing-related task and state what would be lost with another choice. Do not justify the choice using speed alone.
- These public checks are examples of contract evidence, not proof for every possible program or a measure of job readiness. Add a fresh boundary case of your own and explain which mistake it would expose.
Come back after a day and try the transfer task again without opening hints. A durable skill is being able to explain and adapt, not only recognise an answer.
Continue: tuples and unpacking