LearnWave
Learn it. Master it.

Lists

List methods and functions

Pick the right method to change a list.

Some built-in functions work on lists: len(); list(), which makes an empty list or turns a sequence into a list (list('abc') gives ['a', 'b', 'c']); and min(), max() and sum().

List methods that add elements:

  • append(x) adds one element at the end. If x is itself a list, it is added as one element: [1, 2].append([3, 4]) makes [1, 2, [3, 4]].
  • extend(list2) adds each element of list2 at the end: [1, 2].extend([3, 4]) makes [1, 2, 3, 4].
  • insert(i, x) puts x at index i, moving the rest along.

Methods that find or remove elements:

  • count(x): how many times x occurs.
  • index(x): the position of the first x; a ValueError if x is not there. For [7, 3, 7], index(7) is 0.
  • remove(x): deletes the first x only (ValueError if absent).
  • pop(i): deletes the element at index i and returns it; with no index, it removes the last element.

Methods that rearrange:

  • reverse() reverses the list in place.
  • sort() sorts it in place; sort(reverse = True) sorts it in descending order.

Compare these with the function sorted(list1), which returns a new sorted list and leaves list1 unchanged.

Methods change the list; sorted() makes a new one.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.