Python List Methods

Chapter 23 10 mins

Learning outcomes:

  1. Indexing elements using index()
  2. Adding elements using append(), insert() and extend()
  3. Removing elements using pop() and remove()
  4. Counting occurences using count()
  5. Sorting lists using sort()
  6. Reversing the order of elements using reverse()

index()

To determine the index of an element in a list, use the index() method.

list.index(item)

item is the value whose index you wish to retrieve.

Let's see where could we possibly use index().

Suppose we want to remove 20 from the list nums shown below. We can do so using the pop() method by providing it with the index of 20 in the list nums.

nums = [10, 20, 30]
nums.pop(1) # remove the second element

print(nums)
[10, 30]

In this case, we knew the index of 20 and so provided it directly to pop(), but imagine if we didn't know of it. In such a scenario, we can first index the item we want to remove and then pass the index to pop().

Below we use index() and pop() together to remove 20 from nums.

nums = [10, 20, 30]
nums.pop(nums.index(20))

print(nums) # [10, 30]

Keep in mind that indexing an element in a list that doesn't exist in it, would result in an error, as shown below:

nums = [10, 20, 30]
print(nums.index(40))
Traceback (most recent call last): File "stdin", line 2, in <module> print(nums.index(200)) ValueError: 200 is not in list

append()

The append() method is used to add an element to the end of a list.

list.append(item)

Commonly, in other programming languages such as Java, JavaScript, PHP, this functionality is referred to as 'push'. Pushing an element onto an array (which is analogous to a list in Python) means adding it at the end of the array.

One thing to note is that append() method mutates a list i.e changes it in-place.

Consider the following code, where we add three elements to an empty list, one by one, using three separate calls to append():

cities = []

cities.append('London')
cities.append('Paris')
cities.append('Berlin')

print(cities)
['London', 'Paris', 'Berlin']

insert()

Just like append(), the insert() method is used to add stuff to a list. However, it isn't limited only to the end of the list — it can add an element at any given position.

list.insert(index, item)

The first index argument specifies the index where to add the given item.

If the index is preoccupied in the list, then all the elements from that point onwards are shifted one step forward.

Below shown is an extremely simple example:

cities = ['London', 'Berlin']

cities.insert(1, 'Paris')
print(cities)
['London', 'Paris', 'Berlin']

We insert the value 'Paris' at index 1. The value previously at this index — 'Berlin' — is shifted one step forward. That is, it's now accessible at index 2 (rather than at index 1).

extend()

The extend() method is one of the three ways to add elements to a list; the other two being append() and insert().

list.extend(iterable)

It takes in an iterable and adds each of its elements at the end of main list in the order they are in the given list. And, as with append() and insert(), it mutates the list it's called on.

Suppose we have two different lists of numbers, and want to print the remainder of each them when divided by 2. Separately dealing with both these lists wouldn't sound sensible — we would have to loop over each list individually:

a = [10, 5, 51]
b = [30, 9]

for num in a:
    print(num, '%', 2, '=', num % 2)

for num in b:
    print(num, '%', 2, '=', num % 2)
10 % 2 = 0
5 % 2 = 1
51 % 2 = 1
30 % 2 = 0
9 % 2 = 1

What's sensible is that we merge these two lists into one single list and perform the processing on that.

a = [10, 5, 51]
b = [30, 9]
a.extend(b)

for num in a:
    print(num, '%', 2, '=', num % 2)
10 % 2 = 0
5 % 2 = 1
51 % 2 = 1
30 % 2 = 0
9 % 2 = 1

pop()

The pop() method is used to remove an element at a given position, from a list, and return it.

If called without an argument, it removes the last element from the list. This behavior is consistent with the similar-sounding method/function in other languages — 'pop' means to remove the last element.

Below, we remove the last two elements of nums one by one using pop():

nums = [10, 20, 30]

nums.pop()
print(nums)

nums.pop()
print(nums)
[10, 20]
[10]

As stated above, pop() additionally returns the deleted element, which can be particularly useful if we want to process the element before deleting it.

Extending the code above, following we print out the removed element:

nums = [10, 20, 30]

print('Removing', nums.pop())
print(nums)

print()

print('Removing', nums.pop())
print(nums)
Removing 30
[10, 20]

Removing 20
[10]

Let's now use pop() to delete an element from a given position:

nums = [10, 20, 30]

print('Removing', nums.pop(0))
print(nums)
Removing 10
[20, 30]

The element at index 0 has been deleted and returned.

Note that it's possible to provide negative arguments to pop(), in which case, as usual, they are evaluated from the end of the list.

Consider the code below, where we remove the last element from nums:

nums = [10, 20, 30]

print('Removing', nums.pop(-1))
print(nums)

When called without an argument, pop() defaults the position to -1 i.e it removes the last element from the given list.

remove()

When removing elements from a list, the pop() method works wonders, given that we know the index of each element.

However, sometimes the indexes are not known, but rather the actual values are known.

For instance, suppose you want to remove all 0's from a list of numbers, without knowing the index of each occurence.

In such cases, it's handy to use the remove() method.

list.remove(value)

The remove() method takes a single argument that is the value to remove. If the value exists in the list, it removes it, or otherwise throws a ValueError.

Note that remove() doesn't return the element removed. This is because, when we call l.remove(element) to remove element from a list l, we already know what's being removed i.e element — we are specifying it ourself!

It would've been senseless if remove() returned the element removed.

Consider the following:

nums = [1, 2, 3, 4, 5]

nums.remove(1)
print(nums)
[2, 3, 4, 5]

The statement nums.remove(1) doesn't remove the element at index 1 from nums. Rather, it literally removes the element 1, wherever it exists. In this case, it existed at the beginning of the list, and therefore got removed from there.

When using remove(), you need to be sure that the list has the element you wish to remove. If the element doesn't exist, you get an error:

nums = [1, 2, 3, 4, 5]

nums.remove(6)
Traceback (most recent call last): File "stdin", line 3, in <module> nums.remove(6) ValueError: list.remove(x): x not in list

count()

To see how many times does a given element appear in a list, we can use the count() method.

It takes the value whose count is desired, and returns back an integer denoting its count.

Consider the code below:

nums = [0, 0, 1, 5, 3, 1, 1, 3]

print('Count of 0:', nums.count(0))
print('Count of 1:', nums.count(1))
print('Count of 10:', nums.count(10))
Count of 0: 2
Count of 1: 3
Count of 10: 0

sort()

The sort() method, as the name suggests, sorts a list into increasing or decreasing order. It mutates the original list.

list.sort(reverse=False, key=None)

Let's start with a simple example:

Here we have a list of numbers ordered randomly.

nums = [11, -3, 6, 10, 2, 50, 9, -10]

To sort this list in increasing order, we'll call sort() on it, without any sort of arguments:

nums = [11, -3, 6, 10, 2, 50, 9, -10]

nums.sort()
print(nums)
[-10, -3, 2, 6, 9, 10, 11, 50]

Note that sort() doesn't return anything. It just reorders a given list in a particular order. To work with the sorted list, we have to refer back to it (which is now sorted), as we did above in line 4.

To sort in decreasing order, we set the reverse keyword argument to True, as follows:

nums = [11, -3, 6, 10, 2, 50, 9, -10]

nums.sort(reverse=True)
print(nums)
[50, 11, 10, 9, 6, 2, -3, -10]

We'll learn more about sorting lists in the next Python List Sorting chapter.

reverse()

To reverse the order of elements of a list, we can employ the reverse() method. Akin to sort(), it mutates the given list and doesn't return anything.

Following we reverse the order of the randomly-ordered nums list above:

nums = [11, -3, 6, 10, 2, 50, 9, -10]

nums.reverse()
print(nums)
[-10, 9, 50, 2, 10, 6, -3, 11]

The reverse() method can be really helpful when we want to sort a list, that is already sorted in decreasing order, into increasing order; or vice versa.

An example is shown below:

nums = [10, 20, 30, 40]

nums.reverse()
print(nums)

Here nums is already sorted in increasing order. To sort it in decreasing order, we call nums.reverse().

Note that we could've also called nums.sort(reverse=True) to sort the list in decreasing order, but that would've been inefficient, as compared to nums.reverse().

This is because in the former case, multiple comparisons have to be made to judge which element would come first, which would come second and so on. In the latter case, we just have to iterate over the list, starting from its end, and create a new list out of it.