Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 149 ยท Data Structures

List Methods

A practical tour of Python list methods. Add items with append, extend and insert, remove them with remove, pop and clear, then sort, reverse, search, count and copy.

In Lists you learned to create lists, read items by index and replace them. Most real work with lists, though, means changing their size and order: adding a new message to a chat, removing a finished task, sorting a leaderboard. Python lists come with a set of built-in methods for exactly these jobs.

A method is a function that belongs to an object and is called with a dot: tasks.append("email Sam"). List methods have one big thing in common that this lesson keeps coming back to: almost all of them change the list in place and return None. Knowing which methods change the list and which return something new will save you from a whole family of bugs.

Adding items: append, extend and insert

There are three ways to add items to an existing list:

Method What it does
append(x) Adds one item, x, at the end
extend(iterable) Adds every item of an iterable at the end
insert(i, x) Inserts x before index i, shifting later items right
Python append, extend and insert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last example shows the difference between append and extend clearly: append([3, 4]) adds a single item that happens to be a list, giving [1, 2, [3, 4]]. Use extend() (or +=, which does the same thing for lists) when you want to add several items.

Watch out for extend() with a string: strings are iterable, so letters.extend("hi") adds "h" and "i" as two separate items.

Note: append() is very fast at any list size. insert(0, x) has to shift every existing item one place to the right, so it gets slower as the list grows. If you often add or remove at the front, look at collections.deque in the collections lesson.

Removing items: remove, pop, clear and del

Removal comes in two flavors: by value and by position.

Tool Removes Returns
remove(x) The first item equal to x None
pop() The last item The removed item
pop(i) The item at index i The removed item
clear() Every item None
del items[i] The item at index i (a statement, not a method) Nothing
Python Removing items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two errors to know:

  • remove(x) raises ValueError if x isn't in the list. Check with if x in items: first, or handle the error (see Exceptions).
  • pop() on an empty list raises IndexError: pop from empty list.

pop() is the method to use when you need the removed value. Together with append(), it turns a list into a stack: the last item added is the first one taken out.

Python A stack for undo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

while history: uses truthiness: an empty list is falsy, so the loop stops when everything has been popped.

Sorting and reversing

sort() puts the list in order in place. reverse() flips the current order in place. Both return None.

Python sort() and reverse()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Key points about sorting:

  • Strings sort by character code, so every uppercase letter comes before every lowercase one. key=str.lower compares lowercase versions while keeping the original strings.
  • The key argument takes a function that's called once per item; the list is sorted by the results. key=len sorts by length. You'll write your own key functions with lambda.
  • Python's sort is stable: items that compare equal keep their original relative order. In the example, "banana" and "Cherry" both have 6 letters, so the length sort keeps them in the order the case-insensitive sort left them.
  • Items must be comparable with each other. Numbers and strings can't be mixed.

sort() vs sorted()

Warning: numbers = numbers.sort() is a classic bug. sort() returns None, so this line sorts the list and then throws it away, leaving numbers set to None.

Use the method when you want to change the list itself, and the built-in sorted() when you want a new sorted list and need to keep the original:

Python
prices = [9.5, 3.0, 7.25]

cheap_first = sorted(prices)    # new list: [3.0, 7.25, 9.5]
print(prices)                   # unchanged: [9.5, 3.0, 7.25]

prices.sort()                   # changes prices itself

The same pair exists for reversing: items.reverse() changes the list, and reversed(items) gives an iterator over it backward without changing anything.

Searching and counting: index and count

Python index() and count()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • count(x) returns how many items equal x, and returns 0 when there are none.
  • index(x) returns the position of the first match. Optional start and end arguments limit where it looks. If there's no match it raises ValueError, so check with in first when the value might be missing.

Copying: copy()

As you saw in Lists, b = a makes two names for one list. copy() creates a new list with the same items:

Python Shallow copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

copy() is a shallow copy: the outer list is new, but the items inside are the same objects. For lists of numbers or strings, that's all you need. For nested lists, use copy.deepcopy() to copy every level.

Quick reference

Method Changes the list? Returns
append(x) Yes None
extend(iterable) Yes None
insert(i, x) Yes None
remove(x) Yes None (or ValueError)
pop(i=-1) Yes The removed item (or IndexError)
clear() Yes None
sort(key=None, reverse=False) Yes None
reverse() Yes None
index(x, start, end) No An index (or ValueError)
count(x) No An integer
copy() No A new, shallow copy

Run help(list) in a Python shell to see them all with short descriptions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is nums after nums = [1, 2] and nums.append([3, 4])?

    append adds its argument as a single item. Use extend([3, 4]) to add 3 and 4 separately.
  2. 2. What does pets.pop() return when pets = ["cat", "dog", "owl"]?

    Without an argument, pop() removes and returns the last item.
  3. 3. After data = [3, 1, 2] and data = data.sort(), what is data?

    sort() sorts in place and returns None, and that None is then assigned to data. Use data.sort() alone, or data = sorted(data).
  4. 4. What does ["b", "a", "b"].remove("b") leave in the list?

    remove() deletes only the first item equal to the value, so the second "b" stays.
  5. 5. Which call returns a new sorted list and leaves items unchanged?

    The built-in sorted() always returns a new list. items.copy().sort() sorts a copy but returns None, so the sorted copy is lost.

Summary

  • Add with append(x) (one item), extend(iterable) (many items) or insert(i, x) (at a position).
  • Remove by value with remove(x), by position with pop(i) or del items[i], or everything with clear().
  • pop() returns the removed item; with append() it makes a list behave like a stack.
  • sort() and reverse() change the list and return None; sorted() and reversed() leave it alone.
  • sort(key=..., reverse=True) controls the order; sorting is stable.
  • index(x) finds a position (or raises ValueError), count(x) counts matches, copy() makes a shallow copy.

Next: Slicing, where you'll take whole ranges of items out of lists and strings in a single expression.