Python – List Methods
Python provides a variety of built-in list methods that allow you to manipulate, modify, search, and organize your lists with ease.
These methods make list handling powerful and efficient.
Python List Method Summary
Here's a table of the most commonly used list methods:
| Method | Description |
|---|---|
append() | Adds an element to the end of the list |
extend() | Adds elements from another iterable |
insert() | Inserts an element at a specific position |
remove() | Removes the first matching element |
pop() | Removes element at the specified position |
clear() | Removes all elements from the list |
index() | Returns the index of the first match |
count() | Returns the number of occurrences |
sort() | Sorts the list in place |
reverse() | Reverses the list in place |
copy() | Returns a shallow copy of the list |
Examples of List Methods
1. append()
Adds an item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)Output:
['apple', 'banana', 'cherry']2. extend()
Adds elements from another list or iterable.
a = [1, 2]
b = [3, 4]
a.extend(b)
print(a)
Output
[1, 2, 3, 4]3. insert()
Inserts an item at a given index.
fruits = ["apple", "banana"]
fruits.insert(1, "orange")
print(fruits)Output:
['apple', 'orange', 'banana']4. remove()
Removes the first occurrence of a value.
fruits = ["apple", "banana", "apple"]
fruits.remove("apple")
print(fruits)Output:
['banana', 'apple']5. pop()
Removes and returns the item at the given index (or last item if index is not provided).
numbers = [1, 2, 3]
removed = numbers.pop()
print(removed)
print(numbers)Output:
3
[1, 2]6. clear()
Removes all elements from the list.
items = [1, 2, 3]
items.clear()
print(items)Output:
[]7. index()
Returns the index of the first matching element.
fruits = ["apple", "banana", "cherry"]
print(fruits.index("banana"))Output:
18. count()
Counts how many times an element appears.
numbers = [1, 2, 2, 3]
print(numbers.count(2))Output:
29. sort()
Sorts the list in ascending order.
numbers = [4, 2, 1, 3]
numbers.sort()
print(numbers)Output:
[1, 2, 3, 4]10. reverse()
Reverses the order of elements.
items = [1, 2, 3]
items.reverse()
print(items)Output:
[3, 2, 1]11. copy()
Returns a copy of the list.
original = ["a", "b", "c"]
copied = original.copy()
print(copied)Output:
['a', 'b', 'c']Tips
- Mutable: Lists can be changed after creation.
- Chaining: Avoid chaining
append()orsort()with assignment (list = list.append(...)) — these returnNone.