Tracks
/
Python
Python
/
Syllabus
/
List Methods
Li

List Methods in Python

68 exercises

About List Methods

A list is a mutable collection of items in sequence. Like most collections (see the built-ins tuple, dict and set), lists can hold references to any (or multiple) data type(s) - including other lists. They're considered a sequence in Python, and can be copied in whole or in part via slice notation. Like any sequence, elements within lists can be referenced by 0-based index number from the left, or -1-based index number from the right.

Lists support both common and mutable sequence operations such as min(<list>)/max(<list>), <list>.index(), <list>.append() and <list>.reverse(). Items can be iterated over using the for item in <list> construct, and for index, item in enumerate(<list>) when both the element and element index are needed.

Python provides many useful methods for working with lists.

Because lists are mutable, list-methods alter the original list object passed into the method. If mutation is undesirable, a shallow copy (at minimum_) of the original list needs to be made via slice or <list>.copy().

Adding Items

Adding items to the end of an existing list can be done via <list>.append(<item>):

>>> numbers = [1, 2, 3]
>>> numbers.append(9)

>>> numbers
[1, 2, 3, 9]

Rather than appending, <list>.insert(<index>, <item>) adds the item to a specific index within the list. <index> is the index of the item before which you want the new item to appear. <item> is the element to be inserted.

Note: If <index> is 0, the item will be added to the start of the list. If <index> is greater than the final index on the list, the item will be added in the final position -- the equivalent of using <list>.append(<item>).

>>> numbers = [1, 2, 3]
>>> numbers.insert(0, -2)

>>> numbers
[-2, 1, 2, 3]

>>> numbers.insert(1, 0)

>>> numbers
[-2, 0, 1, 2, 3]

An iterable can be combined with an existing list (concatenating the two) via <list>.extend(<iterable>). <list>.extend(<iterable>) will unpack the supplied iterable, adding its elements in the same order to the end of the target list (using <list>.append(<item>) in this circumstance would add the entire iterable as a single item.).

>>> numbers = [1, 2, 3]
>>> other_numbers = [5, 6, 7]

>>> numbers.extend(other_numbers)

>>> numbers
[1, 2, 3, 5, 6, 7]

>>> numbers.extend([8, 9])

>>> numbers
[1, 2, 3, 5, 6, 7, 8, 9]

Removing Items

<list>.remove(<item>) can be used to remove an element from the list. <list>.remove(<item>) will throw a ValueError if the element is not present in the list.

>>> numbers = [1, 2, 3]
>>> numbers.remove(2)

>>> numbers
[1, 3]

# Trying to remove a value that is not in the list throws a ValueError.
>>> numbers.remove(0)
ValueError: list.remove(x): x not in list

Alternatively, using <list>.pop(<index>) method will both remove and return an element for use.

<list>.pop(<index>) takes one optional parameter: the index of the element to remove and return. If the optional <index> argument is not specified, the last element of the list will be removed and returned. If <index> is a higher number than the final index of the list, an IndexError will be thrown.

>>> numbers = [1, 2, 3]
>>> numbers.pop(0)
1

>>> numbers
[2, 3]
>>> numbers.pop()
3

>>> numbers
[2]

# This will throw an error because there is only index 0.
>>> numbers.pop(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

All items can be removed from a list via <list>.clear(). It does not take any parameters.

>>> numbers = [1, 2, 3]
>>> numbers.clear()

>>> numbers
[]

Reversing and reordering

The order of list elements can be reversed in place with <list>.reverse(). This will mutate the original list.

>>> numbers = [1, 2, 3]
>>> numbers.reverse()

>>> numbers
[3, 2, 1]

List elements can be sorted in place using <list>.sort(). Internally, Python uses Timsort to arrange the elements. The default order is ascending. The Python docs have additional tips and techniques for sorting lists effectively.

>>> names = ["Tony", "Natasha", "Thor", "Bruce"]

# The default sort order is *ascending*.
>>> names.sort()

>>> names
["Bruce", "Natasha", "Thor", "Tony"]

To sort a list in descending order, pass a reverse=True argument to the method:

>>> names = ["Tony", "Natasha", "Thor", "Bruce"]
>>> names.sort(reverse=True)

>>> names
["Tony", "Thor", "Natasha", "Bruce"]

For cases where mutating the original list is undesirable, the built-in functions sorted() and reversed() can be used. sorted(<list>) will return a sorted copy, and takes the same parameters as <list>.sort(). reversed(<list>) returns an iterator that yields the list's items in reverse order. Iterators will be covered in detail in another exercise.

Occurrences of an item in a list

Finding the number of occurrences of an element in a list can be done with the help of <list>.count(<item>). It returns the total number of times <item> appears as an element in the list.

>>> items = [1, 4, 7, 8, 2, 9, 2, 1, 1, 0, 4, 3]

>>> items.count(1)
3

Finding the index of items

<list>.index(<item>) will return the index number of the first occurrence of an item passed in. If there are no occurrences, a ValueError is raised. Indexing is 0-based from the left, meaning the position of the first item is index 0. Indexing from the right is also supported, starting with index -1.

>>> items = [7, 4, 1, 0, 2, 5]
>>> items.index(4)
1

>>> items.index(10)
ValueError: 10 is not in list

Providing start and end indices will search within a specific section of the list:

>>> names = ["Tina", "Leo", "Thomas", "Tina", "Emily", "Justin"]
>>> names.index("Tina")
0

>>> names.index("Tina", 2, 5)
3

If the exact position of an element is not needed, the built-in in operator is more efficient for verifying membership.

>>> names = ["Tina", "Leo", "Thomas", "Tina", "Emily", "Justin"]

>>> "Thomas" in names
True

Making Copies

Remember that variables in Python are names that point to underlying objects. Names can be bound or re-bound to different objects over the life of a program. Assigning a list object to a new variable name does not copy the object or any of its referenced data. The new name and old name will both point at the same list object. Additionally, lists are a container type object - to save space, containers only hold references to member items, not the items themselves. This "optimization" can have unintended consequences for the unwary.

<list>.copy() will create a new list object, but will not create new objects for the referenced list elements -- the copy is "shallow". A shallow copy is usually enough when you want to add or remove items from one of the list objects without modifying the other. But if there is any chance that the underlying elements of a list might be accidentally mutated (thereby mutating all related shallow copies), copy.deepcopy() in the copy module should be used to create a complete or "deep" copy of all references and objects.

For a detailed explanation of names, values, list, and nested list behavior, take a look at this excellent blog post from Ned Batchelder -- Names and values: making a game board. Shallow vs Deep Copying of Python Objects also offers a good rundown of copy considerations.

Edit via GitHub The link opens in a new window or tab

Learn List Methods

Practicing is locked

Unlock 6 more exercises to practice List Methods