List methods in Python: append, sort, and filter
Data doesn't sit still. A new sales day arrives, sizes need ranking, low stock needs flagging. Lists come with methods for each, and one of them has a famous trap.
The big idea
List methods like append() and sort() change a list in place, while functions like sorted() leave it alone and return a new one.
See it in code
append() adds one value to the end of a list, changing the list itself:
daily_tees = [42, 57, 38, 64, 71, 95, 88]
daily_tees.append(72)
print("Days recorded:", len(daily_tees))
print(f"Average per day: {sum(daily_tees) / len(daily_tees):.1f}")Days recorded: 8 Average per day: 65.9
The list now has eight items, and because the average divides by len(), it adjusted without any other edit.
There are two ways to sort, and they behave differently. sorted() returns a new list. .sort() rearranges the original and returns None:
size_sales = [18, 64, 120, 97, 41]
ranked = sorted(size_sales, reverse=True)
print("sorted() gave back:", ranked)
print("Original untouched:", size_sales)
result = size_sales.sort()
print(".sort() gave back:", result)
print("Original now:", size_sales)sorted() gave back: [120, 97, 64, 41, 18] Original untouched: [18, 64, 120, 97, 41] .sort() gave back: None Original now: [18, 41, 64, 97, 120]
.sort() did its work on size_sales directly, so there was nothing to hand back. Writing size_sales = size_sales.sort() would replace your data with None.
Filtering means building a new list from the items that pass a test. Here two parallel lists produce the colors that need restocking:
colors = ["sage", "oat", "charcoal", "navy", "clay"]
stock = [12, 3, 25, 0, 8]
reorder_point = 10
restock = []
for i in range(len(colors)):
if stock[i] < reorder_point:
restock.append(colors[i])
print("Restock:", restock)Restock: ['oat', 'navy', 'clay']
Start empty, loop, append what qualifies. reorder_point is a business rule in one named place, so changing the threshold is a one-line edit.
Append-in-a-loop builds results in every domain: signals from a price series, matches from a search, cleaned rows from a messy file.
Try it yourself
Add .remove("navy") after the loop and print the list. Then try restock.insert(0, "sage"). Finally, change reorder_point to 15 and predict which color joins the list.
The common mistake
Assigning the result of an in-place method. ranked = size_sales.sort() sets ranked to None. If you want a sorted copy, call sorted(size_sales); if you want to sort in place, call .sort() on its own line.
What it unlocks
The filter loop above compresses into one line as a list comprehension. To pick items out of the result, see indexing and slicing.