Python Lists: Ordered, Mutable Collections
The list is Python’s workhorse collection: ordered, changeable, and happy to hold any mix of types. Most of the data you handle day to day, from a batch of order IDs to a queue of pending tasks, lands in a list first. This tutorial uses OrdersPortal order records to cover the operations you reach for constantly — indexing, slicing, adding and removing items, sorting, and a first look at comprehensions — and ends with a guide to when a list is the wrong tool.
What you’ll learn
Section titled “What you’ll learn”- How to create lists and read or change items by index, including slicing and negative indices.
- How to add and remove items with
append,insert,remove,pop, andextend. - A first look at list comprehensions for building lists from other data.
- How to sort, test membership, and choose between list, tuple, and set.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or newer installed (run
python --versionto check). - Comfort with variables, basic types, and
forloops. - A way to run a script: save code as
.pyand runpython filename.py.
1. Create and inspect a list
Section titled “1. Create and inspect a list”A list is an ordered, mutable sequence written with square brackets. It holds any types and keeps its order. Use len() to count items.
orders = ["ORD-001", "ORD-002", "ORD-003"]print(len(orders)) # 3Verify: The script prints 3.
2. Index and slice
Section titled “2. Index and slice”Access a single item with list[index]. Indices start at 0; negative indices count from the end. A slice list[start:stop] returns a new list from start up to, but not including, stop.
orders = ["ORD-001", "ORD-002", "ORD-003", "ORD-004"]print(orders[0]) # ORD-001print(orders[-1]) # ORD-004print(orders[1:3]) # ['ORD-002', 'ORD-003']print(orders[:2]) # ['ORD-001', 'ORD-002']Verify: The script prints each value shown in the comment. Out-of-range indexing raises IndexError; an out-of-range slice just stops at the end.
3. Add items with append, insert, and extend
Section titled “3. Add items with append, insert, and extend”append adds one item to the end. insert places an item at a chosen index. extend appends every item from another iterable, flattening them into the list.
orders = ["ORD-001", "ORD-002"]orders.append("ORD-003") # add to the endorders.insert(0, "ORD-000") # insert at index 0orders.extend(["ORD-004", "ORD-005"])print(orders)Verify: The script prints ['ORD-000', 'ORD-001', 'ORD-002', 'ORD-003', 'ORD-004', 'ORD-005'].
4. Remove items with remove and pop
Section titled “4. Remove items with remove and pop”remove(value) deletes the first item equal to value and raises ValueError if it is absent. pop(index) removes and returns the item at that index, defaulting to the last item.
orders = ["ORD-001", "ORD-002", "ORD-003", "ORD-002"]orders.remove("ORD-002") # removes the first matchlast = orders.pop() # removes and returns 'ORD-002'print(orders, last)Verify: The script prints ['ORD-001', 'ORD-003'] ORD-002.
5. Build a list with a comprehension
Section titled “5. Build a list with a comprehension”A list comprehension builds a new list from an iterable in one expression: [expression for variable in iterable if condition]. The optional if filters which items to keep. See the comprehensions intro for the full picture.
amounts = [149.99, 49.99, 19.99, 299.00]large = [amt for amt in amounts if amt > 100]print(large) # [149.99, 299.0]Verify: The script prints [149.99, 299.0].
6. Sort a list
Section titled “6. Sort a list”list.sort() sorts the list in place and returns None. sorted(list) returns a new sorted list and leaves the original alone. Pass reverse=True to sort descending.
amounts = [149.99, 49.99, 299.00, 19.99]ascending = sorted(amounts)amounts.sort(reverse=True)print(ascending) # [19.99, 49.99, 149.99, 299.0]print(amounts) # [299.0, 149.99, 49.99, 19.99]Verify: The first print shows ascending order, the second descending.
7. Test membership
Section titled “7. Test membership”The in operator checks whether a value is present. It scans the list, so it is O(n). For frequent lookups over many items, a set is faster.
orders = ["ORD-001", "ORD-002", "ORD-003"]print("ORD-002" in orders) # Trueprint("ORD-999" in orders) # FalseVerify: The script prints True, then False.
8. Choose list, tuple, or set
Section titled “8. Choose list, tuple, or set”Reach for a list when order matters and items may change. Use a tuple when the sequence is fixed and should not change, which also lets it serve as a dict key. Use a set when you need uniqueness or fast membership tests and order does not matter.
statuses_list = ["shipped", "pending", "shipped"] # order kept, duplicates allowedstatus_codes = (200, 404, 500) # fixed, immutableunique_statuses = {"shipped", "pending", "cancelled"} # no duplicates, fast lookupVerify: The script runs without error. Each type is tuned for a different job.
Complete working example
Section titled “Complete working example”Save this as orders_lists.py and run python orders_lists.py.
"""Manage a small batch of OrdersPortal orders with list operations."""
orders = [ {"id": "ORD-001", "amount": 149.99, "status": "shipped"}, {"id": "ORD-002", "amount": 49.99, "status": "pending"}, {"id": "ORD-003", "amount": 299.00, "status": "shipped"}, {"id": "ORD-004", "amount": 19.99, "status": "cancelled"},]
# Add a new orderorders.append({"id": "ORD-005", "amount": 89.99, "status": "pending"})
# Remove the cancelled oneorders = [o for o in orders if o["status"] != "cancelled"]
# Sort by amount, then keep only shipped ordersshipped = [o for o in sorted(orders, key=lambda o: o["amount"]) if o["status"] == "shipped"]
print("shipped (cheapest first):", [o["id"] for o in shipped])print("statuses present:", set(o["status"] for o in orders))print("ORD-003 shipped?", any(o["id"] == "ORD-003" and o["status"] == "shipped" for o in orders))Expected output:
shipped (cheapest first): ['ORD-001', 'ORD-003']statuses present: {'shipped', 'pending'}ORD-003 shipped? TrueCommon mistakes
Section titled “Common mistakes”appendwhen you meantextend.orders.append(["ORD-004", "ORD-005"])adds the list as a single nested element. Useextendto flatten the items in.- Mutating while iterating. Removing items from the list you are looping over shifts indices and skips items. Iterate over a copy (
for o in orders[:]:) or build a new list with a comprehension. - Using a list for membership lookups.
value in my_listscans every item. If you test membership often on a large collection, convert to asetfirst. - Confusing
sort()withsorted().orders.sort()sorts in place and returnsNone, sonew = orders.sort()assignsNonetonew. Usesorted(orders)when you need a new list. - Treating a slice as the list. Slicing returns a new list, so changing the slice does not change the original. Assign back explicitly when you want to keep the change.
Next steps
Section titled “Next steps”- Comprehensions intro — list, dict, set comprehensions, and generator expressions in depth.
- Tuples — the immutable cousin of a list, and when to prefer it.
- Sets — uniqueness and set operations such as union and intersection.
- Lambda functions — the
keyargument used withsortedabove.
Related pages
Section titled “Related pages”- Python basics index — overview of every basics page in one place.
- Dictionaries — keyed collections that often pair with lists of records.
- Loops —
forloops over lists and the iteration that powers comprehensions.
Official references
Section titled “Official references”- docs.python.org: More on lists — list methods and use.
- docs.python.org: Sequence types — indexing, slicing, and operations shared with tuples.
- docs.python.org: List comprehensions — the comprehension syntax.
- docs.python.org: Sorting how-to —
sortedandlist.sortwith keys.