Skip to Content

10 useful Examples to Master Python List Methods

Python 3 has a number of built-in data structures, including lists.

Data structures provide us with a way to organize and store data, and we can use built-in methods to retrieve or manipulate that data.

It is important to keep in mind that lists are mutable — or changeable — data types.

Unlike strings, which are immutable, whenever we use a method on a list you will be affecting the list itself and not a copy of the list.

Get Your Free Linux training!

Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!

Python 3 List

A list is a data structure in Python that is a mutable, ordered sequence of elements. Mutable means that you can change the items inside, while ordered sequence is in reference to index location. The first element in a list will always be located at index 0. Each element or value that is inside of a list is called an item.

Just as strings are defined as characters between quotes, lists are defined by having different data types between square brackets [ ].

Also, like strings, each item within a list is assigned an index, or location, for where that item is saved in memory.

Lists are also known as a data collection. Data collections are simply data types that can store multiple items.

Python List Methods

As a mutable, or changeable, ordered sequence of elements, lists are very flexible data structures in Python.

Python List methods enable us to work with lists in a sophisticated manner.

  • sort(): Sorts the list in ascending order.
  • type(list): It returns the class type of an object.
  • append(): Adds one element to a list.
  • extend(): Adds multiple elements to a list.
  • index(): Returns the first appearance of a particular value.
  • max(list): It returns an item from the list with a max value.
  • min(list): It returns an item from the list with a min value.
  • len(list): It gives the overall length of the list.
  • clear(): Removes all the elements from the list.
  • insert(): Adds a component at the required position.
  • count(): Returns the number of elements with the required value.
  • pop(): Removes the element at the required position.
  • remove(): Removes the primary item with the desired value.
  • reverse(): Reverses the order of the list.
  • copy():  Returns a duplicate of the list.

Python 3 List Methods

Method Description
append(x) Adds an item (x) to the end of the list. This is equivalent to a[len(a):] = [x].
extend(iterable) Extends the list by appending all the items from the iterable. This allows you to join two lists together. This method is equivalent to a[len(a):] = iterable.
insert(i, x) Inserts an item at a given position. The first argument is the index of the element before which to insert. For example, a.insert(0, x) inserts at the front of the list.
remove(x) Removes the first item from the list that has a value of x. Returns an error if there is no such item.
pop([i]) Removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.
clear() Removes all items from the list. Equivalent to del a[:].
index(x[, start[, end]]) Returns the position of the first list item that has a value of x. Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
count(x) Returns the number of times x appears in the list.
sort(key=None, reverse=False) Sorts the items of the list in place. The arguments can be used to customize the operation.
keySpecifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compares the elements directly).reverseBoolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
reverse() Reverses the elements of the list in place.
copy() Returns a shallow copy of the list. Equivalent to a[:].
Use the copy() method when you need to update the copy without affecting the original list. If you don’t use this method (eg, if you do something like list2 = list1), then any updates you do to list2 will also affect list1.
The example at the side demonstrates this.
List Functions
The following Python functions can be used on lists.
Method Description
len(s) Returns the number of items in the list.
The len() function can be used on any sequence (such as a string, bytes, tuple, list, or range) or collection (such as a dictionary, set, or frozen set).
list([iterable]) The list() constructor returns a mutable sequence list of elements. The iterable argument is optional. You can provide any sequence or collection (such as a string, list, tuple, set, dictionary, etc). If no argument is supplied, an empty list is returned.
Strictly speaking, list([iterable]) is actually a mutable sequence type.
max(iterable, *[, key, default])
or
max(arg1, arg2, *args[, key])
Returns the largest item in an iterable (eg, list) or the largest of two or more arguments.
The key argument specifies a one-argument ordering function like that used for sort().
The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
If more than one item shares the maximum value, only the first one encountered is returned.
min(iterable, *[, key, default])
or
min(arg1, arg2, *args[, key])
Returns the smallest item in an iterable (eg, list) or the smallest of two or more arguments.
The key argument specifies a one-argument ordering function like that used for sort().
The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
If more than one item shares the minimum value, only the first one encountered is returned.
range(stop)
or
range(start, stop[, step])
Represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
It can be used along with list() to return a list of items between a given range.
Strictly speaking, range() is actually a mutable sequence type.

 

 

Python List methods – list.append()

append() adds an element to the list. Here is an example:

a = [1, 2]
b = [6, 7, 8]
a.append(3)
a.append(b)
print(a)

# this will return:
# [1, 2, 3, [6, 7, 8]]

Python List methods – list.extend()

append() will simply ‘tack’ on whatever value passed in. However, to properly add integrate one list into another, we should use extend().

Note that this will only work with iterable values and not single values. Here is an example:

a = [1, 2]
b = [6, 7, 8]
a.extend(b)
print(a)

# this will return:
# [1, 2, 6, 7, 8]

Python List methods – list.clear()

clear() will remove all items from the list in Python. Here is an example:

a = [1, 2]
a.clear()

# this will return
# []

Python List methods – list.copy()

copy() will create a copy of a list in Python. Here is an example:

a = [1, 2]
b = a.copy()
print(b)

# this will return
# [1, 2]

Python List methods – list.count()

count() will count the number of times a value appears in a list. Here is an example:

message = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
countme = message.count(‘l’)
print(countme)

# this will return
# 3

Python List methods – list.index()

index() will find the index position of a value in a list. Lists start their index at 0. It is also good to note that it will stop at the first instance of the matched value. For example:

message = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
indexme = message.index(‘l’)
print(indexme)

# this will return
# 2

Python List methods – list.insert()

Use insert() if we want to add a value into a specific position inside our list rather than append it at the end. For example:

message = [‘H’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
message.insert(1, ‘e’)
print(message)

# this will return
# [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]

Python List methods – list.remove()

We can remove a specific item from the list by using remove(). Note that, similar to index(), it will only remove the first instance of the matched value. To remove all matched values, we wil need to put them through a loop. For example:

letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
letters.remove(‘f’)
print(letters)

# this will return
# [‘a’, ‘b’, ‘c’, ‘f’]

Here’s an example of a loop to remove all values inside a list. We pair this with range() to know how many times it appears.

letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]

for item in range(letters.count(‘f’))
letters.remove(‘f’)

Python List methods – list.pop()

pop() will eject the last item from the array. For example:

letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
letters.pop()
print(letters)

# this will return:
# [‘a’, ‘b’, ‘f’, ‘c’]
If we try to pop an empty array, we will get an IndexError

Python List methods – list.reverse()

reverse() will do as it says reverses the list. For example:

letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
letters.reverse()
print(letters)

# this will return
# [‘f’, ‘c’, ‘f’, ‘b’, ‘a’]

Python List methods – list.sort()

sort() will rearrange your list to ascending order. It’s good to note that character order is based on the ASCII table.

sortme = [‘c’,’a’,’d’,’b’]
sortme.sort()
print(sortme)

# this will return:
# [‘a’, ‘b’, ‘c’, ‘d’]