All List Methods
Python lists come with built-in methods that allow you to add, remove, search, modify, and organize elements efficiently.
Below is a complete, method-by-method explanation, where each method includes:
- Clear introduction
- Proper syntax
- Working code example
append()
What it does
Adds one element to the end of the list.
Syntax
python
list.append(item)
Example
python
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
extend()
What it does
Adds multiple elements from another iterable to the list.
Syntax
python
list.extend(iterable)
Example
python
numbers = [1, 2]
numbers.extend([3, 4, 5])
print(numbers)
insert()
What it does
Inserts an element at a specific index.
Syntax
python
list.insert(index, item)
Example
python
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits)
remove()
What it does
Removes the first occurrence of a specified value.
Syntax
python
list.remove(value)
Example
python
numbers = [1, 2, 3, 2]
numbers.remove(2)
print(numbers)
pop()
What it does
Removes and returns an element at a given index
(default: last element).
Syntax
python
list.pop(index)
Example
python
fruits = ["apple", "banana", "cherry"]
item = fruits.pop()
print(item)
print(fruits)
clear()
What it does
Removes all elements from the list.
Syntax
python
list.clear()
Example
python
numbers = [1, 2, 3]
numbers.clear()
print(numbers)
index()
What it does
Returns the index of the first occurrence of a value.
Syntax
python
list.index(value)
Example
python
fruits = ["apple", "banana", "cherry"]
print(fruits.index("banana"))
count()
What it does
Returns how many times a value appears in the list.
Syntax
python
list.count(value)
Example
python
numbers = [1, 2, 2, 3, 2]
print(numbers.count(2))
sort()
What it does
Sorts the list in ascending order by default.
Syntax
python
list.sort(key=None, reverse=False)
Example
python
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)
reverse()
What it does
Reverses the order of elements in the list.
Syntax
python
list.reverse()
Example
python
numbers = [1, 2, 3]
numbers.reverse()
print(numbers)
copy()
What it does
Creates a shallow copy of the list.
Syntax
python
list.copy()
Example
python
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a)
print(b)
Summary Table (Quick Revision)
| Method | Purpose |
|---|---|
append() | Add one item |
extend() | Add multiple items |
insert() | Insert at index |
remove() | Remove by value |
pop() | Remove by index |
clear() | Remove all items |
index() | Find position |
count() | Count occurrences |
sort() | Sort list |
reverse() | Reverse list |
copy() | Copy list |
Key Notes
- Most list methods modify the original list
pop()returns a value, others usually don’tsort()andreverse()returnNone- Lists are mutable, so methods act in-place
This topic completes the core list operations required for:
- Data processing
- Real-world applications
- Interviews
- Competitive programming