I. Overview of List Methods
Lists (list) are the most commonly used mutable sequence type in Python, supporting dynamic addition, deletion, replacement, and rearrangement of elements.
Unlike strings and tuples, a list's contents can be modified directly after creation, without needing to create a new list each time.
1. Categories of Common List Methods
Python lists provide a rich set of built-in methods, which can be divided into the following categories by function:
| Category | Common Methods | Main Purpose |
|---|---|---|
| Adding elements | append() |
Add a single element at the end |
| Adding elements | extend() |
Append elements from an iterable at the end |
| Inserting elements | insert() |
Insert an element at a specified position |
| Removing elements | remove() |
Remove the first matching element |
| Removing elements | pop() |
Remove and return the element at a specified position |
| Removing elements | clear() |
Clear the list |
| Finding elements | index() |
Find the position of an element's first occurrence |
| Counting elements | count() |
Count the occurrences of an element |
| Sorting | sort() |
Sort in place |
| Reversing | reverse() |
Reverse in place |
| Copying | copy() |
Create a shallow copy |
2. Differences Between List Methods and Built-in Functions
List methods are called through an object, whereas built-in functions are called by function name.
numbers = [3, 1, 2]
# List method
numbers.sort()
# Built-in function
result = sorted(numbers)
print(numbers)
# [1, 2, 3]
print(result)
# [1, 2, 3]
The differences:
list.sort(): modifies the original list directly and returnsNone.sorted(): does not modify the original list and returns a new sorted list.
Understanding whether a method modifies the original object is one of the most important fundamentals when working with lists.
II. Methods for Adding Elements
Lists support several ways to add elements, among which append(), extend(), and insert() are the most commonly used.
1. append(): Add a Single Element at the End
append() is used to add a single element at the end of a list.
Syntax:
list.append(element)
Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
# [1, 2, 3, 4]
append() adds only one object at a time.
Even if a list is passed in, the entire list is added as a single element.
numbers = [1, 2, 3]
numbers.append([4, 5])
print(numbers)
# [1, 2, 3, [4, 5]]
Here the structure of the list has changed, and the last element is itself a list.
2. extend(): Extend a List
extend() is used to append each element from an iterable one by one to the end of a list.
Syntax:
list.extend(iterable)
Example:
numbers = [1, 2, 3]
numbers.extend([4, 5])
print(numbers)
# [1, 2, 3, 4, 5]
Unlike append(), extend() does not add the entire list as a single element; instead, it appends each of its elements one by one.
numbers = [1, 2, 3]
numbers.append([4, 5])
print(numbers)
# [1, 2, 3, [4, 5]]
numbers = [1, 2, 3]
numbers.extend([4, 5])
print(numbers)
# [1, 2, 3, 4, 5]
extend() accepts not only lists but also other iterables.
numbers = [1, 2, 3]
# Append a tuple
numbers.extend((4, 5))
# Append a string
numbers.extend("AB")
# Append a range object
numbers.extend(range(6, 8))
print(numbers)
# [1, 2, 3, 4, 5, 'A', 'B', 6, 7]
Note that strings are also iterable objects, so they are appended character by character.
3. insert(): Insert an element at a specified position
insert() is used to insert an element at a specified index position.
Syntax:
list.insert(index, element)
Example:
numbers = [10, 20, 40, 50]
numbers.insert(2, 30)
print(numbers)
# [10, 20, 30, 40, 50]
After insertion, the original element at that position and all subsequent elements shift to the right.
Negative indices can also be used:
numbers = [10, 20, 30]
numbers.insert(-1, 25)
print(numbers)
# [10, 20, 25, 30]
Note the following:
- An index of
0means insertion at the beginning. - An index of
len(list)means insertion at the end. - When the index is out of range, it is treated as the boundary position, rather than raising
IndexErroras normal index access would. - Negative indices are adjusted based on the list length.
For example:
numbers = [1, 2, 3]
numbers.insert(100, 4)
print(numbers)
# [1, 2, 3, 4]
numbers.insert(-100, 0)
print(numbers)
# [0, 1, 2, 3, 4]
4. Comparison of append(), extend(), and insert()
| Method | Insertion position | Content added | Modifies the original list |
|---|---|---|---|
append(x) |
End | A single object | Yes |
extend(iterable) |
End | Elements from an iterable | Yes |
insert(i, x) |
Specified position | A single object | Yes |
What all three have in common is that they directly modify the original list and return None.
numbers = [1, 2, 3]
result = numbers.append(4)
print(result)
# None
Therefore, do not mistake the return value of a list-modifying method for the modified list.
III. Methods for deleting elements
Lists provide several deletion operations for different scenarios.
1. remove(): Delete elements by value
remove() is used to remove the first element in the list that equals the specified value.
Syntax:
list.remove(value)
Example:
numbers = [10, 20, 30, 20, 40]
numbers.remove(20)
print(numbers)
# [10, 30, 20, 40]
When the list contains multiple identical elements, remove() only removes the first match.
If the element does not exist, a ValueError is raised.
numbers = [10, 20, 30]
# numbers.remove(100)
# ValueError: list.remove(x): x not in list
If you are unsure whether the element exists, you can check first:
if 100 in numbers:
numbers.remove(100)
However, note that this performs one membership lookup and one removal lookup. This is usually fine for typical business code; if you need to handle large amounts of data efficiently, consider other data structures or filtering in a single pass.
2. pop(): Remove and return an element
pop() is used to remove the element at a specified position and return the removed element.
Syntax:
list.pop(index)
If no index is specified, the last element is removed by default.
numbers = [10, 20, 30, 40]
value = numbers.pop()
print(value)
# 40
print(numbers)
# [10, 20, 30]
Specifying an index:
numbers = [10, 20, 30, 40]
value = numbers.pop(1)
print(value)
# 20
print(numbers)
# [10, 30, 40]
Using a negative index:
numbers = [10, 20, 30, 40]
value = numbers.pop(-2)
print(value)
# 30
print(numbers)
# [10, 20, 40]
If the list is empty, or the index is out of range, an IndexError is raised.
3. clear(): Clear the List
clear() is used to remove all elements from a list.
numbers = [10, 20, 30]
numbers.clear()
print(numbers)
# []
clear() keeps the list object itself and only clears its elements.
numbers = [1, 2, 3]
alias = numbers
numbers.clear()
print(numbers)
# []
print(alias)
# []
Both variables reference the same list, so whichever variable you use, you see the same cleared list.
4. Using del to Delete Elements
del is a Python statement, not a list method.
It can delete a specified index, a slice, or even a variable binding.
numbers = [10, 20, 30, 40]
del numbers[1]
print(numbers)
# [10, 30, 40]
Delete multiple elements:
numbers = [10, 20, 30, 40, 50]
del numbers[1:4]
print(numbers)
# [10, 50]
Clear the list:
numbers = [1, 2, 3]
del numbers[:]
print(numbers)
# []
5. Comparison of remove(), pop(), clear(), and del
| Operation | Deletion Criterion | Returns the Deleted Element? | Modifies the Original List? |
|---|---|---|---|
remove(x) |
Element value | No, returns None |
Yes |
pop(i) |
Element index | Yes | Yes |
clear() |
All elements | No, returns None |
Yes |
del list[i] |
Element index | No | Yes |
del list[i:j] |
Slice range | No | Yes |
Selection suggestions:
- If you know the element's value: use
remove(). - If you need to retrieve and delete an element: use
pop(). - If you need to clear the list: use
clear(). - If you need to delete a specified index or range: use
del.
IV. Lookup and Counting Methods
Lists provide two commonly used lookup and counting methods: index() and count().
1. index(): Find an Element's Index
index() returns the position where the specified element first appears.
Syntax:
list.index(value, start, stop)
Where:
value: the element to search for.start: the position at which to start searching; optional.stop: the position at which to stop searching, exclusive; optional.
Example:
numbers = [10, 20, 30, 20, 40]
print(numbers.index(20))
# 1
Specify the search range:
numbers = [10, 20, 30, 20, 40]
print(numbers.index(20, 2))
# 3
When searching for the first matching element, you can use start and stop to limit the range.
If the element does not exist, a ValueError is raised.
numbers = [10, 20, 30]
# numbers.index(100)
# ValueError
Safe search:
target = 100
if target in numbers:
position = numbers.index(target)
else:
position = -1
print(position)
# -1
For business scenarios with frequent lookups, repeatedly using in and index() rescans the list each time. Consider building a dictionary or set index.
2. count(): Count Element Occurrences
count() is used to count the number of times the specified element appears in the list.
Syntax:
list.count(value)
Example:
numbers = [10, 20, 20, 30, 20, 40]
print(numbers.count(20))
# 3
print(numbers.count(100))
# 0
Even if the element does not exist, count() does not raise an exception; it returns 0.
3. Count duplicate elements in a list
You can count duplicate elements by combining sets and dictionaries.
numbers = [1, 2, 2, 3, 3, 3, 4]
counts = {}
for number in numbers:
counts[number] = counts.get(number, 0) + 1
print(counts)
# {1: 1, 2: 2, 3: 3, 4: 1}
If you only need to count frequencies, you can use the standard library Counter:
from collections import Counter
numbers = [1, 2, 2, 3, 3, 3, 4]
counts = Counter(numbers)
print(counts)
# Counter({3: 3, 2: 2, 1: 1, 4: 1})
4. Comparison of index() and count()
| Method | Purpose | When the element is not found |
|---|---|---|
index(x) |
Returns the index of the first occurrence | Raises ValueError |
count(x) |
Returns the number of occurrences | Returns 0 |
Both usually require traversing the list, with a time complexity of O(n).
V. Sorting method sort()
sort() is used to sort a list in place.
It is one of the most important list methods and works with numbers, strings, and objects that can be compared according to specified rules.
1. Default ascending sort
numbers = [5, 2, 8, 1, 9, 3]
numbers.sort()
print(numbers)
# [1, 2, 3, 5, 8, 9]
By default, it sorts in ascending order.
2. Descending sort
You can sort in descending order by using reverse=True.
numbers = [5, 2, 8, 1, 9, 3]
numbers.sort(reverse=True)
print(numbers)
# [9, 8, 5, 3, 2, 1]
3. Specify the sorting rule with key
The key parameter specifies the comparison basis used for sorting.
names = ["Tom", "Alexander", "Bob", "Catherine"]
names.sort(key=len)
print(names)
# ['Tom', 'Bob', 'Alexander', 'Catherine']
Here, the strings are sorted in ascending order by length.
4. Sort by object attribute
In real-world development, it is often necessary to sort a list of dictionaries or a list of objects.
students = [
{"name": "Alice", "score": 90},
{"name": "Bob", "score": 85},
{"name": "Cindy", "score": 95}
]
students.sort(key=lambda item: item["score"])
print(students)
Sorts by score in ascending order.
Descending order:
students.sort(
key=lambda item: item["score"],
reverse=True
)
5. Sort by multiple fields
You can specify multiple sorting criteria using a tuple.
students = [
{"name": "Alice", "age": 20, "score": 90},
{"name": "Bob", "age": 18, "score": 90},
{"name": "Cindy", "age": 20, "score": 95},
{"name": "David", "age": 18, "score": 85}
]
students.sort(
key=lambda item: (
item["score"],
item["age"]
)
)
Sort rules:
- First, sort by score in ascending order.
- If scores are the same, sort by age in ascending order.
Tuple comparison follows lexicographical order rules.
6. Stability of Sorting
Python list sorting is stable sorting.
Stable sorting means: if two elements have the same sort key, their relative order remains unchanged after sorting.
students = [
{"name": "Alice", "score": 90},
{"name": "Bob", "score": 85},
{"name": "Cindy", "score": 90},
{"name": "David", "score": 85}
]
students.sort(key=lambda item: item["score"])
for student in students:
print(student["name"], student["score"])
Output:
Bob 85
David 85
Alice 90
Cindy 90
Bob and David retained their original relative order, and so did Alice and Cindy.
7. Return Value of sort()
sort() modifies the original list in place and returns None.
numbers = [3, 1, 2]
result = numbers.sort()
print(result)
# None
print(numbers)
# [1, 2, 3]
Incorrect usage:
numbers = [3, 1, 2]
# numbers = numbers.sort()
After execution, numbers will be rebound to None.
Correct usage:
numbers = [3, 1, 2]
numbers.sort()
8. Difference Between sorted() and sort()
sorted() is a built-in function, not a list method.
numbers = [5, 2, 8, 1]
result = sorted(numbers)
print(result)
# [1, 2, 5, 8]
print(numbers)
# [5, 2, 8, 1]
Comparison:
| Comparison Dimension | list.sort() |
sorted() |
|---|---|---|
| Type | List method | Built-in function |
| Modifies original list | Yes | No |
| Return value | None |
New sorted list |
| Supported objects | Lists | Any iterable object |
Supports key |
Yes | Yes |
Supports reverse |
Yes | Yes |
If you need to preserve the original data, prefer sorted().
9. Underlying Sorting Algorithm of sort()
Python list sorting uses the Timsort algorithm.
Timsort is a stable adaptive sorting algorithm that can take advantage of existing ordered runs in the data.
Main features:
- Stable sorting.
- Can exploit existing ordered ranges.
- Worst-case time complexity is O(n log n).
- Generally has good performance on partially ordered data.
- Requires extra auxiliary space during sorting.
In engineering, you do not need to implement sorting algorithms yourself; prefer Python's built-in sorting capabilities.
VI. Reversing a List with reverse()
reverse() is used to reverse the order of elements in a list in place.
1. Basic Usage
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)
# [5, 4, 3, 2, 1]
reverse() directly modifies the original list.
2. Return Value of reverse()
numbers = [1, 2, 3]
result = numbers.reverse()
print(result)
# None
print(numbers)
# [3, 2, 1]
reverse() returns None; do not assign it to the original list variable.
3. Difference Between reverse() and Slice Reversal
numbers = [1, 2, 3, 4]
# In-place reversal
numbers.reverse()
print(numbers)
# [4, 3, 2, 1]
Slice reversal:
numbers = [1, 2, 3, 4]
result = numbers[::-1]
print(result)
# [4, 3, 2, 1]
print(numbers)
# [1, 2, 3, 4]
Differences:
| Operation | Modifies the original list | Creates a new list |
|---|---|---|
reverse() |
Yes | No |
[::-1] |
No | Yes |
reversed() |
No | Returns a reverse iterator |
4. Using reversed() to iterate in reverse
reversed() is a built-in function that returns a reverse iterator.
numbers = [1, 2, 3, 4]
result = reversed(numbers)
print(list(result))
# [4, 3, 2, 1]
print(numbers)
# [1, 2, 3, 4]
You can also iterate directly:
for number in reversed(numbers):
print(number)
If you only need to read data from back to front and do not need to create a new reversed list, you can use reversed().
VII. Methods for copying lists
Lists are mutable objects, so when copying a list, you need to understand object reference relationships.
1. Direct assignment is not copying
numbers = [1, 2, 3]
other = numbers
other.append(4)
print(numbers)
# [1, 2, 3, 4]
print(other)
# [1, 2, 3, 4]
This does not create a new list.
numbers and other point to the same list object.
2. Using copy() to copy a list
copy() can create a new list object.
numbers = [1, 2, 3]
copied = numbers.copy()
copied.append(4)
print(numbers)
# [1, 2, 3]
print(copied)
# [1, 2, 3, 4]
The outer structures of the two lists are independent of each other.
3. Copying using slicing
numbers = [1, 2, 3]
copied = numbers[:]
print(copied)
# [1, 2, 3]
print(copied is numbers)
# False
4. Copying using list()
numbers = [1, 2, 3]
copied = list(numbers)
print(copied)
# [1, 2, 3]
For lists, this also creates a new outer list.
5. Shallow copy and nested objects
copy(), slicing, and list() are all shallow copies.
A shallow copy only copies the outermost container and does not recursively copy inner objects.
data = [
[1, 2],
[3, 4]
]
copied = data.copy()
print(copied is data)
# False
print(copied[0] is data[0])
# True
Modifying an inner list:
copied[0].append(100)
print(data)
# [[1, 2, 100], [3, 4]]
Because both outer lists still reference the same inner lists.
6. Using deepcopy() for deep copying
If you need to copy the inner objects in a nested list, you can use copy.deepcopy().
import copy
data = [
[1, 2],
[3, 4]
]
copied = copy.deepcopy(data)
copied[0].append(100)
print(data)
# [[1, 2], [3, 4]]
print(copied)
# [[1, 2, 100], [3, 4]]
A deep copy recursively processes objects and follows the objects' own copy protocols.
However, it does not guarantee that all resources can be copied; external resources such as file handles and network connections generally cannot be copied simply.
7. Comparison of four copying methods
| Copy Method | Creates New Outer List | Recursively Copies Inner Objects |
|---|---|---|
other = numbers |
No | No |
numbers.copy() |
Yes | No |
numbers[:] |
Yes | No |
list(numbers) |
Yes | No |
copy.deepcopy(numbers) |
Yes | Yes, handled according to the copy protocol |
8. In-place Modification Mechanism of Lists
In-place modification is an important feature of Python lists.
It means directly modifying the contents of an existing list object rather than creating a new list and then replacing the original object.
1. What Is In-place Modification?
numbers = [1, 2, 3]
print(id(numbers))
numbers.append(4)
print(id(numbers))
In common Python implementations, append() modifies the same list object, so the object identity remains unchanged.
You can observe the object identity with id().
Note that the specific implementation and numeric form of id() depend on the Python implementation; the numeric value from one output should not be treated as a fixed address.
2. Difference Between In-place Modification and Rebinding
In-place modification:
numbers = [1, 2, 3]
alias = numbers
numbers.append(4)
print(alias)
# [1, 2, 3, 4]
Rebinding:
numbers = [1, 2, 3]
alias = numbers
numbers = numbers + [4]
print(numbers)
# [1, 2, 3, 4]
print(alias)
# [1, 2, 3]
The core difference between the two operations:
- In-place modification: changes the contents of the original object.
- Rebinding: makes the variable point to another object.
3. Common In-place Modification Operations
The following list operations usually modify the original list directly:
| Operation | In-place Modification |
|---|---|
append() |
Yes |
extend() |
Yes |
insert() |
Yes |
remove() |
Yes |
pop() |
Yes |
clear() |
Yes |
sort() |
Yes |
reverse() |
Yes |
| Slice assignment | Yes |
del deleting list elements |
Yes |
+= extending a list |
Usually |
The following operations usually create a new list:
| Operation | Behavior |
|---|---|
numbers + other |
Creates a new list |
numbers * n |
Creates a new list |
numbers[:] |
Creates a shallow copy |
numbers.copy() |
Creates a shallow copy |
list(numbers) |
Creates a shallow copy |
sorted(numbers) |
Creates a new sorted list |
numbers[::-1] |
Creates a reversed list |
4. Shared Reference Issues with In-place Modification
If multiple variables point to the same list, an in-place modification to the list through any one variable will affect what the other variables see.
numbers = [1, 2, 3]
a = numbers
b = numbers
a.append(4)
print(numbers)
# [1, 2, 3, 4]
print(b)
# [1, 2, 3, 4]
This is not a copy failure; rather, multiple variables already reference the same object.
5. Why List Modification Methods Usually Return None
Many list modification methods return None in order to clearly distinguish modification operations from result-producing operations.
For example:
numbers = [3, 1, 2]
numbers.sort()
numbers.reverse()
Rather than:
numbers = sorted(numbers)
numbers = list(reversed(numbers))
The former modifies an existing object, while the latter creates a new object and rebinds the variable.
This helps reduce misuse and makes the side effects of the code clearer.
9. The Difference Between In-Place Modification and Immutable Sequences
Not all sequences in Python allow in-place modification.
1. Lists Are Mutable Sequences
numbers = [1, 2, 3]
numbers[0] = 100
print(numbers)
# [100, 2, 3]
Lists allow elements to be modified.
2. Tuples Are Immutable Sequences
numbers = (1, 2, 3)
# Modification is not allowed
# numbers[0] = 100
# TypeError
After a tuple is created, its element references cannot be modified.
3. Strings Are Immutable Sequences
text = "Python"
# Modification is not allowed
# text[0] = "J"
# TypeError
If you need to modify the contents of a string, you need to create a new string: