Lesson 15 of 34 · Lists & Tuples
Python List Methods and Sorting
Lists come with a toolbox of built-in methods for adding, removing, finding and sorting items. Knowing which method to reach for — and whether it changes the list in place or returns a new one — is a big step toward writing fluent Python.
Adding items
bag = ["rope"]
bag.append("torch") # add one item to the end
bag.extend(["map", "potion"]) # add every item from another iterable
bag.insert(0, "sword") # insert at a position
print(bag) # ['sword', 'rope', 'torch', 'map', 'potion']
+ also joins lists, but it builds a new list: [1, 2] + [3] is [1, 2, 3].
Removing items
bag.remove("map") # remove the first matching value
last = bag.pop() # remove and return the last item -> "potion"
first = bag.pop(0) # remove and return the item at index 0 -> "sword"
del bag[0] # delete by index, nothing returned
bag.clear() # empty the list
remove() raises ValueError if the value isn't there, and pop() raises IndexError on an empty list — check with in or if bag: first when unsure.
Finding and counting
rolls = [3, 6, 2, 6, 1]
print(rolls.index(6)) # 1 (position of the first 6)
print(rolls.count(6)) # 2
print(6 in rolls) # True
print(min(rolls), max(rolls), sum(rolls)) # 1 6 18
Sorting: sort() versus sorted()
Python offers two ways to sort, and the difference matters:
scores = [70, 95, 82]
ranked = sorted(scores) # returns a NEW sorted list
print(ranked) # [70, 82, 95]
print(scores) # [70, 95, 82] <- original unchanged
scores.sort() # sorts THIS list in place, returns None
print(scores) # [70, 82, 95]
Both accept reverse=True for descending order, and a key function that computes what to sort by:
words = ["Banana", "fig", "apple", "Cherry"]
print(sorted(words)) # ['Banana', 'Cherry', 'apple', 'fig']
print(sorted(words, key=str.lower)) # ['apple', 'Banana', 'Cherry', 'fig']
print(sorted(words, key=len)) # ['fig', 'apple', 'Banana', 'Cherry']
print(sorted(words, key=len, reverse=True)) # ['Banana', 'Cherry', 'apple', 'fig']
Notice that plain string sorting puts all uppercase letters before lowercase ones — key=str.lower fixes that. Python's sort is stable: items that compare equal keep their original relative order, which is why "Banana" stays ahead of "Cherry" (both have six letters).
To reverse a list without sorting, use items.reverse() (in place) or items[::-1] (new list).
Lists and strings
Two string methods connect text and lists:
words = "fire ice storm".split() # ['fire', 'ice', 'storm']
print(", ".join(words)) # fire, ice, storm
Common mistakes
items = items.sort(): in-place methods such assort(),append()andreverse()returnNone, so this replaces your list withNone. Use eitheritems.sort()oritems = sorted(items).appendvsextend:bag.append(["a", "b"])adds one item — a nested list. Useextendto add each element.- Removing items while looping over the same list skips elements. Build a new list instead.
- Sorting mixed types:
sorted([3, "a"])raisesTypeError, because Python can't compare numbers with strings.
Assignment
Write three functions. None of them may modify the list they receive:
top_scores(scores, n)returns thenhighest scores, highest first. If there are fewer thannscores, return all of them, sorted.sort_by_length(words)returns a new list of the words sorted from shortest to longest. Words of equal length keep their original order.dedupe(items)returns a new list without duplicates, keeping the first occurrence of each item in its original position.
top_scores([50, 90, 70, 100, 85], 3) # [100, 90, 85]
sort_by_length(["kiwi", "fig", "banana", "apple"]) # ['fig', 'kiwi', 'apple', 'banana']
dedupe([3, 1, 3, 2, 1]) # [3, 1, 2]Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Sorting and searching lists in other languages
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .