Python provides a wide range of built-in methods for list manipulation. Here are some of the most commonly used methods:
len(): returns the length of a list
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
append(): adds an element to the end of a list
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
extend(): adds the elements of one list to the end of another list
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
my_list1.extend(my_list2)
print(my_list1) # Output: [1, 2, 3, 4, 5, 6]
insert(): inserts an element at a specified position in a list
my_list = [1, 2, 3, 5]
my_list.insert(3, 4)
print(my_list) # Output: [1, 2, 3, 4, 5]
remove(): removes the first occurrence of an element from a list
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5]
pop(): removes and returns the element at a specified position in a list
my_list = [1, 2, 3, 4, 5]
print(my_list.pop(2)) # Output: 3
print(my_list) # Output: [1, 2, 4, 5]
index(): returns the index of the first occurrence of an element in a list
my_list = [1, 2, 3, 4, 5]
print(my_list.index(3)) # Output: 2
sort(): sorts the elements of a list in ascending order
my_list = [4, 1, 3, 2, 5]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4, 5]
reverse(): reverses the order of the elements in a list
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
In summary, Python provides a wide range of built-in methods for list manipulation, such as len(), append(), extend(), insert(), remove(), pop(), index(), sort(), and reverse(). These methods can be used to manipulate lists in various ways, such as adding and removing elements, sorting and reversing elements, and finding the index of an element.