Skip to content

Computer Science · Ch 9 — Lists

List Methods and Built-in Functions

9.4

List Methods and Built-in Functions

The list data type comes with a rich set of built-in methods and functions for everyday programming: measuring a list, building one, adding and removing elements, searching, rearranging, and summarising. The chapter collects them in Table 9.1; here each one is explained with its behaviour and an example.

Method / functionWhat it does
len()Returns the number of elements in the list
list()Creates an empty list, or builds a list from a sequence
append()Adds one element at the end
extend()Adds each element of another list at the end
insert()Inserts an element at a given index
count()Counts how many times an element occurs
index()Returns the index of the first occurrence
remove()Deletes the first occurrence of a value
pop()Returns and deletes an element by index (default: last)
reverse()Reverses the list in place
sort()Sorts the list in place
sorted()Returns a new sorted list, original unchanged
min(), max(), sum()Smallest element, largest element, total of elements

len() — length of a list

Passed a list as argument, len() returns its length, i.e. the total number of elements:

>>> scores = [55, 60, 65, 70, 75]
>>> len(scores)
5

list() — creating a list

With no argument, list() creates an empty list:

>>> items = list()
>>> items
[]

With a sequence as argument, it builds a list out of that sequence's items — for example, a string becomes a list of its characters:

>>> word = 'stack'
>>> chars = list(word)
>>> chars
['s', 't', 'a', 'c', 'k']

append() — add a single element at the end

append() attaches the single element passed as argument to the end of the list:

>>> nums = [3, 6, 9, 12]
>>> nums.append(15)
>>> nums
[3, 6, 9, 12, 15]

That single element can itself be a list — in which case the whole inner list becomes one new element (a nested list), not several:

>>> nums = [3, 6, 9, 12]
>>> nums.append([15, 18])
>>> nums
[3, 6, 9, 12, [15, 18]]

extend() — add each element of another list

extend() takes a list as argument and appends each of its elements individually to the end of the given list. Compare this with append() above:

>>> nums = [3, 6, 9]
>>> more = [12, 15]
>>> nums.extend(more)
>>> nums
[3, 6, 9, 12, 15]

insert() — add an element at a chosen position

insert(index, element) places the element at the given index, shifting later elements right:

>>> nums = [10, 30, 40]
>>> nums.insert(1, 20)     # put 20 at index 1
>>> nums
[10, 20, 30, 40]
>>> nums.insert(0, 5)      # put 5 at the front
>>> nums
[5, 10, 20, 30, 40]

count() — occurrences of an element

count() returns the number of times the given element appears in the list; a value that never appears gives 0:

>>> vals = [7, 2, 7, 9, 7, 4]
>>> vals.count(7)
3
>>> vals.count(100)
0

index() — position of the first occurrence

index() returns the index of the first occurrence of the element. If the element is not present at all, a ValueError is generated:

>>> vals = [7, 2, 7, 9, 7, 4]
>>> vals.index(7)
0
>>> vals.index(50)
ValueError: 50 is not in list

remove() — delete by value

remove() deletes the given value from the list. If the value occurs several times, only the first occurrence is removed; if it is not present, a ValueError is generated:

>>> vals = [4, 8, 12, 8, 16]
>>> vals.remove(8)
>>> vals
[4, 12, 8, 16]
>>> vals.remove(99)
ValueError: list.remove(x): x not in list

pop() — return and delete by index

pop(index) returns the element at the given index and simultaneously removes it from the list:

>>> vals = [11, 22, 33, 44, 55]
>>> vals.pop(2)
33
>>> vals
[11, 22, 44, 55]

Called with no argument, pop() returns and removes the last element:

>>> vals = [11, 22, 44, 55]
>>> vals.pop()
55
>>> vals
[11, 22, 44]

Note the contrast: remove() works by value and returns nothing; pop() works by index and hands the deleted element back to you.

reverse() — flip the order in place

reverse() reverses the order of the elements of the list in place — the list itself is modified and nothing is returned:

>>> vals = [14, 3, 92, 27]
>>> vals.reverse()
>>> vals
[27, 92, 3, 14]

>>> pets = ['Dog', 'Cat', 'Parrot', 'Rabbit']
>>> pets.reverse()
>>> pets
['Rabbit', 'Parrot', 'Cat', 'Dog']

sort() — arrange in place

sort() arranges the elements of the list in ascending order, again in place (the original ordering is lost). Strings are sorted alphabetically, numbers numerically:

>>> pets = ['Dog', 'Cat', 'Parrot', 'Rabbit']
>>> pets.sort()
>>> pets
['Cat', 'Dog', 'Parrot', 'Rabbit']

Passing the keyword argument reverse = True sorts in descending order instead:

>>> vals = [14, 3, 92, 27]
>>> vals.sort(reverse = True)
>>> vals
[92, 27, 14, 3]

sorted() — a sorted copy

The built-in function sorted() takes a list as parameter and creates a new list with the same elements arranged in sorted order. The original list is left exactly as it was — this is the key difference from sort():

>>> vals = [31, 8, 57, 12]
>>> ordered = sorted(vals)
>>> vals            # unchanged
[31, 8, 57, 12] …
Table 9.1Built-in functions for list manipulations
MethodDescriptionExample
len()Returns the length of the list passed as the argument>>> list1 = [10,20,30,40,50]
>>> len(list1)
5
list()Creates an empty list if no argument is passed

Creates a list if a sequence is passed as an argument
>>> list1 = list()
>>> list1
[ ]
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']
append()Appends a single element passed as an argument at the end of the list

The single element can also be a list
>>> list1 = [10,20,30,40]
>>> list1.append(50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
extend()Appends each element of the list passed as argument to the end of the given list>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
insert()Inserts an element at a particular index in the list>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
count()Returns the number of times a given element appears in the list>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0
index()Returns index of the first occurrence of the element in the list. If the element is not present, ValueError is generated>>> list1 = [10,20,30,20,40,10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list
remove()Removes the given element from the list. If the element is present multiple times, only the first occurrence is removed. If the element is not present, then ValueError is generated>>> list1 = [10,20,30,40,50,30]
>>> list1.remove(30)
>>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x):x not in list
pop()Returns the element whose index is passed as parameter to this function and also removes it from the list. If no parameter is given, then it returns and removes the last element of the list>>> list1 = [10,20,30,40,50,60]
>>> list1.pop(3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
reverse()Reverses the order of elements in the given list>>> list1 = [34,66,12,89,28,99]
>>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1 = [ 'Tiger' ,'Zebra' , 'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger']
sort()Sorts the elements of the given list in-place>>>list1 = ['Tiger','Zebra','Lion', 'Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]