Velamuvi AIAcademy

Lesson 17 of 30 · Collections

List Methods

The Python list methods you will use every day: add, remove, sort, count and copy items, plus min, max and sum, with runnable examples.

  • 7 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • How to add items anywhere in a list
  • Three ways to remove items
  • How to sort a list, and the difference between sort() and sorted()
  • How to copy a list safely

Lists come with built-in tools

A method is an action that belongs to a value, called with a dot. You have already used append(). Lists have several more methods that save you from writing loops by hand.

Adding items

Try it yourselfPython
tasks = ["write code", "test code"]

tasks.append("deploy")            # add to the end
tasks.insert(0, "plan")           # add at index 0
tasks.extend(["monitor", "rest"]) # add several items at once

print(tasks)
  • append(item) adds one item to the end.
  • insert(index, item) adds one item at a position and moves the others along.
  • extend(other_list) adds every item from another list.

Removing items

Try it yourselfPython
colours = ["red", "green", "blue", "green", "yellow"]

colours.remove("green")   # removes the FIRST "green" only
print(colours)

last = colours.pop()      # removes and returns the last item
print("Removed:", last)
print(colours)

first = colours.pop(0)    # removes and returns the item at index 0
print("Removed:", first)
print(colours)

Use remove() when you know the value. Use pop() when you know the position, or when you want to use the removed item.

Sorting

sort() puts the list itself in order. Add reverse=True for largest first.

Try it yourselfPython
scores = [72, 95, 61, 88]

scores.sort()
print(scores)

scores.sort(reverse=True)
print(scores)

names = ["Linus", "Ada", "Grace"]
names.sort()
print(names)

sort() or sorted()?

sort() changes the original list and gives nothing back. sorted() leaves the original alone and returns a new sorted list.

Try it yourselfPython
scores = [72, 95, 61, 88]

ranked = sorted(scores, reverse=True)

print("Original:", scores)
print("Ranked:  ", ranked)

Use sorted() when you still need the original order.

Counting and finding

Try it yourselfPython
votes = ["yes", "no", "yes", "yes", "no"]

print(votes.count("yes"))
print(votes.index("no"))

count() tells you how many times a value appears. index() gives the position of its first appearance.

Quick maths on lists of numbers

These are built-in functions, not methods, so the list goes inside the brackets.

Try it yourselfPython
scores = [72, 95, 61, 88]

print("Lowest: ", min(scores))
print("Highest:", max(scores))
print("Total:  ", sum(scores))
print("Average:", sum(scores) / len(scores))

Copying a list

This surprises almost everyone. Writing b = a does not copy a list. It gives the same list a second name.

Try it yourselfPython
a = [1, 2, 3]
b = a
b.append(4)

print("a:", a)
print("b:", b)

Both show the 4, because a and b are the same list. To get a separate copy, use copy().

Try it yourselfPython
a = [1, 2, 3]
b = a.copy()
b.append(4)

print("a:", a)
print("b:", b)

Common mistakes

Practice exercise

Find the top two scores and print them as a list, largest first.

Your solutionPython
scores = [72, 95, 61, 88]

# Print the two highest scores as a list, highest first.
# Output must be exactly: [95, 88]
Knowledge check

What is the difference between scores.sort() and sorted(scores)?

Summary

  • Add with append(), insert() and extend().
  • Remove with remove(value) or pop(index).
  • sort() changes the list. sorted() returns a new one.
  • min(), max() and sum() work on lists of numbers.
  • b = a does not copy a list. Use a.copy().

Next: a collection that cannot be changed.

Finished reading? Tick it off to track your progress.