Skip to content

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.

  • 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, and extend.
  • A first look at list comprehensions for building lists from other data.
  • How to sort, test membership, and choose between list, tuple, and set.
  • Python 3.9 or newer installed (run python --version to check).
  • Comfort with variables, basic types, and for loops.
  • A way to run a script: save code as .py and run python filename.py.

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)) # 3

Verify: The script prints 3.

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-001
print(orders[-1]) # ORD-004
print(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 end
orders.insert(0, "ORD-000") # insert at index 0
orders.extend(["ORD-004", "ORD-005"])
print(orders)

Verify: The script prints ['ORD-000', 'ORD-001', 'ORD-002', 'ORD-003', 'ORD-004', 'ORD-005'].

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 match
last = orders.pop() # removes and returns 'ORD-002'
print(orders, last)

Verify: The script prints ['ORD-001', 'ORD-003'] ORD-002.

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].

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.

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) # True
print("ORD-999" in orders) # False

Verify: The script prints True, then False.

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 allowed
status_codes = (200, 404, 500) # fixed, immutable
unique_statuses = {"shipped", "pending", "cancelled"} # no duplicates, fast lookup

Verify: The script runs without error. Each type is tuned for a different job.

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 order
orders.append({"id": "ORD-005", "amount": 89.99, "status": "pending"})
# Remove the cancelled one
orders = [o for o in orders if o["status"] != "cancelled"]
# Sort by amount, then keep only shipped orders
shipped = [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? True
  • append when you meant extend. orders.append(["ORD-004", "ORD-005"]) adds the list as a single nested element. Use extend to 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_list scans every item. If you test membership often on a large collection, convert to a set first.
  • Confusing sort() with sorted(). orders.sort() sorts in place and returns None, so new = orders.sort() assigns None to new. Use sorted(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.
  • 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 key argument used with sorted above.
  • Python basics index — overview of every basics page in one place.
  • Dictionaries — keyed collections that often pair with lists of records.
  • Loops — for loops over lists and the iteration that powers comprehensions.