In Python, a list is a built-in data structure that holds an ordered, mutable collection of items. Python provides several in-built methods for list manipulation. Here's a complete and organized explanation of all commonly used in-built list methods:
append()
Purpose: Adds an element at the end of the list.
Syntax: list.append(element)
Example:
fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits) # ['apple', 'banana', 'cherry']
extend()
Purpose: Adds elements from another iterable (list, tuple, etc.) to the end.
Syntax: list.extend(iterable)
Example:
a = [1, 2]
b = [3, 4]
a.extend(b)
print(a) # [1, 2, 3, 4]
insert()
Purpose: Inserts an element at a specified index.
Syntax: list.insert(index, element)
Example:
nums = [1, 3, 4]
nums.insert(1, 2)
print(nums) # [1, 2, 3, 4]
remove()
Purpose: Removes the first occurrence of a value.
Syntax: list.remove(element)
Example:
items = [1, 2, 3, 2]
items.remove(2)
print(items) # [1, 3, 2]
pop()
Purpose: Removes and returns the element at a given index (default is last).
Syntax: list.pop([index])
Example:
items = ['a', 'b', 'c']
last = items.pop()
print(last) # 'c'
clear()
Purpose: Removes all items from the list.
Syntax: list.clear()
Example:
data = [1, 2, 3]
data.clear()
print(data) # []
index()
Purpose: Returns the first index of a value.
Syntax: list.index(value[, start[, end]])
Example:
names = ['Alice', 'Bob', 'Alice']
print(names.index('Alice')) # 0
count()
Purpose: Returns the number of times a value appears.
Syntax: list.count(value)
Example:
a = [1, 2, 2, 3]
print(a.count(2)) # 2
sort()
Purpose: Sorts the list in ascending order (or custom).
Syntax: list.sort(reverse=False, key=None)
Example:
nums = [4, 1, 3]
nums.sort()
print(nums) # [1, 3, 4]
reverse()
Purpose: Reverses the order of elements in the list.
Syntax: list.reverse()
Example:
nums = [1, 2, 3]
nums.reverse()
print(nums) # [3, 2, 1]
copy()
Purpose: Returns a shallow copy of the list.
Syntax: list.copy()
Example:
a = [1, 2]
b = a.copy()
print(b) # [1, 2]
Method | Description |
---|---|
append() |
Add element to end |
extend() |
Add elements from another iterable |
insert() |
Insert element at index |
remove() |
Remove first occurrence of element |
pop() |
Remove and return element at index |
clear() |
Remove all elements |
index() |
Return index of first occurrence |
count() |
Count occurrences of a value |
sort() |
Sort elements (ascending by default) |
reverse() |
Reverse order |
copy() |
Return a shallow copy |