Skip to content
Theory · Lists · lesson 2 of 11

List methods

Picture a checkout queue. People join it at the end, and someone with a small child goes to the front. The cashier serves the first person, and the last one suddenly leaves. The queue is the same queue all along; only who is in it changes.

A list in a program lives the same way: items go into a cart, people leave a queue. For this, a list has its own methods. They are called with a dot, like string methods. But string methods return a new string, while these methods change the list itself:

Python
queue = ["Ann", "Bob"]
queue.append("Kim")
queue.insert(0, "Zoe")
print(queue)  # ['Zoe', 'Ann', 'Bob', 'Kim']
first = queue.pop(0)
last = queue.pop()
print(first, last, queue)  # Zoe Kim ['Ann', 'Bob']
queue.remove("Bob")
queue.extend(["Lee", "Max"])
print(queue)  # ['Ann', 'Lee', 'Max']

Let's see what happens to the queue:

  1. At first, 'Ann' and 'Bob' stand in it.
  2. queue.append("Kim") puts 'Kim' at the end.
  3. queue.insert(0, "Zoe") lets 'Zoe' go to the front, to the place with index 0.
  4. queue.pop(0) takes away the first person, 'Zoe', and returns her: she ends up in first.
  5. queue.pop() with no argument takes away the last person, 'Kim'.
  6. queue.remove("Bob") removes 'Bob', wherever he stands.
  7. queue.extend(["Lee", "Max"]) puts two people at the end at once.

Five methods

Five methods change what a list holds:

  • append(x) adds x to the end of the list;
  • extend(items) adds all the elements of items to the end, like +=;
  • insert(i, x) inserts x before the element at index i;
  • pop(i) removes the element at index i and returns it, and pop() removes the last one;
  • remove(x) removes the first element equal to x.

Two methods stop the program when there is nothing to remove:

  • pop on an empty list stops it with an IndexError;
  • remove of a value that is not in the list stops it with a ValueError.

append and extend

Both methods add to the end, but they count what they add differently.

The append method

append always adds exactly one element. nums.append([3, 4]) puts the whole list [3, 4] at the end as one element, and nums grows by one. In the queue, that is one person carrying a bag, not two people.

The extend method

extend goes over its argument and adds each of its elements separately. After nums.extend([3, 4]), nums grows by two. The form nums += [3, 4] works the same way.

Sorting

Picture books on a shelf. You can rearrange them right on the shelf in alphabetical order. Or you can write the titles on a sheet and order them there, leaving the shelf as it was. Python has both ways:

Python
nums = [3, 1, 2]
ordered = sorted(nums)
print(ordered, nums)  # [1, 2, 3] [3, 1, 2]
nums.sort(reverse=True)
print(nums)  # [3, 2, 1]

Let's go through the example:

  1. The sorted(nums) function builds a new sorted list [1, 2, 3], and nums stays [3, 1, 2].
  2. The nums.sort(reverse=True) method rearranges the elements of nums itself, this time in descending order.

The sort method sorts a list in place: it changes the list itself and returns None. The keyword argument reverse=True sorts in descending order—in both sort and sorted. Strings are sorted alphabetically, with capital letters before lowercase ones.

Interviewers like to ask this: "How does sort differ from sorted?" The answer:

  • sort is a list method: it rearranges the list itself and returns None;
  • sorted is a function: it returns a new list and leaves the original alone.

Strings and lists

A string often has to be cut into parts or put together from parts. Strings have a pair of methods for this.

The split method

split cuts a string into a list of strings, like scissors cutting a ribbon. Without an argument it splits the text on spaces, and several spaces in a row count as one. With an argument it splits on the given string.

The join method

join does the reverse: the string it is called on goes between the elements of the list. It glues only strings: it does not accept a list of numbers and stops the program with a TypeError.

Python
words = "red green  blue".split()
print(words)  # ['red', 'green', 'blue']
print("3,14,15".split(","))  # ['3', '14', '15']
print("-".join(words))  # red-green-blue

Common mistake

The result of sort was assigned back to the variable:

Python
nums = [3, 1, 2]
nums = nums.sort()  # ✗
print(nums[0])
TEXT
TypeError: 'NoneType' object is not subscriptable

sort sorted the list and returned None, and the assignment bound nums to that None. The sorted list is lost, and you cannot take an index of None. Call nums.sort() on its own line, or write nums = sorted(nums).

Key points

  • append, extend, insert, pop and remove change the list itself.
  • append adds exactly one element, and extend adds each element of its argument.
  • sort sorts in place and returns None, and sorted returns a new list.
  • split cuts a string into a list of strings, and join glues a list of strings into one.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way