Skip to content

Module 8 · Python Data Structures — topic 6 of 22

List methods

A tour of every list method: append, extend, insert, remove, pop, clear, index, count, sort, reverse and copy. Learn which change the list in place and which return values.

Beginner 12 min read·Lesson 109 of 306 in Python Programming

Learning objectives

  • Use the eleven list methods correctly
  • Distinguish in-place methods from those returning values
  • Choose sort() or sorted() appropriately

Definition

A tour of every list method: append, extend, insert, remove, pop, clear, index, count, sort, reverse and copy. Learn which change the list in place and which return values.

Introduction

Lists come with eleven methods. Most of them change the list in place and return None; a few return information about the list. Knowing which is which prevents the classic mistake of writing items = items.sort().

Why it matters

Methods are the everyday tools for managing collections: adding orders, removing cancelled ones, sorting results, counting repeats. Using the right method makes code short and intention-revealing.

Detailed explanation

MethodDoesReturns
append(x)adds x at the endNone
extend(iterable)adds every item of iterableNone
insert(i, x)inserts x before index iNone
remove(x)removes the first item equal to xNone (ValueError if absent)
pop(i=-1)removes and returns the item at ithe item
clear()removes all itemsNone
index(x)finds the first position of xint
count(x)counts items equal to xint
sort(key=None, reverse=False)sorts in placeNone
reverse()reverses in placeNone
copy()shallow copynew list

sort() orders the list in place; sorted(items) returns a new sorted list and leaves the original alone.

key= takes a function applied to each item before comparing: sort(key=len) sorts by length, sort(key=str.lower) sorts alphabetically ignoring case.

Sorting mixed types that can’t be compared, such as numbers and strings, raises TypeError.

pop() without an argument removes the last item, which makes a list work as a stack (Module 18).

Syntax

Python
items.append(x)
items.extend([x, y])
items.insert(0, x)
items.remove(x)
last = items.pop()
items.sort(key=len, reverse=True)
  • Mutating methods return None.
  • pop returns the removed item.
  • sort accepts key and reverse.

Code examples

Adding and removing

Python
cart = ["pen"]
cart.append("ink")
cart.extend(["pad", "clip"])
cart.insert(1, "ruler")
print(cart)
cart.remove("pad")
last = cart.pop()
print(cart, last)
Output
['pen', 'ruler', 'ink', 'pad', 'clip']
['pen', 'ruler', 'ink'] clip

Querying and ordering

Python
votes = ["red", "blue", "red", "green", "red"]
print(votes.count("red"), votes.index("blue"))
votes.sort()
print(votes)
votes.reverse()
print(votes)
Output
3 1
['blue', 'green', 'red', 'red', 'red']
['red', 'red', 'red', 'green', 'blue']

More examples

Sorting with keys and the None trap

Python
names = ["chen", "Asha", "ben", "Dev"]
print(sorted(names))
print(sorted(names, key=str.lower))
names.sort(key=len)
print(names)
result = names.sort()
print("sort() returned:", result)
students = [("Asha", 82), ("Ben", 67), ("Chen", 91)]
students.sort(key=lambda s: s[1], reverse=True)
print(students[0])
Output
['Asha', 'Dev', 'ben', 'chen']
['Asha', 'ben', 'chen', 'Dev']
['ben', 'Dev', 'chen', 'Asha']
sort() returned: None
('Chen', 91)

Step-by-step explanation

  • Plain sorting puts capital letters before lower-case ones.
  • key=str.lower compares lower-case versions, giving natural alphabetical order.
  • sort(key=len) orders by length; equal lengths keep their existing order because Python’s sort is stable.
  • The sort() call returns None, while the list itself was sorted.
  • Sorting tuples by their second item ranks students by mark.

Expected output

Running “Sorting with keys and the None trap” prints exactly:

TextOutput
['Asha', 'Dev', 'ben', 'chen']
['Asha', 'ben', 'chen', 'Dev']
['ben', 'Dev', 'chen', 'Asha']
sort() returned: None
('Chen', 91)

Practical applications

  • E-commerce sites sort product lists by price or rating with key=.
  • Undo features pop the last action from a list.
  • Polls count votes with count().

Best practices

  • Use sorted() when you need to keep the original order.
  • Use key= instead of writing custom sorting loops.
  • Check membership before remove() when the item may be missing.

Common mistakes

Assigning the result of sort()

Avoid

items = items.sort()

Prefer

items.sort() # or items = sorted(items)

sort() returns None, so the list is lost.

append versus extend

Avoid

items.append([4, 5]) # adds one nested list

Prefer

items.extend([4, 5])

append adds its argument as a single item; extend adds each item.

Key takeaways

  • append, extend, insert, remove, pop, clear, sort and reverse change the list.
  • Most mutating methods return None; pop returns the item.
  • sort(key=..., reverse=...) controls ordering.

Try it yourself

  1. 1
    Sort a list of words by their last letter using key=.
  2. 2
    Remove every occurrence of 0 from a list using a while loop with remove().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic