Here are some commonly used list methods in Python:
-
append(x): Adds an itemxto the end of the list.my_list.append(5) -
extend(iterable): Extends the list by appending elements from an iterable.my_list.extend([6, 7]) -
insert(i, x): Inserts an itemxat a given positioni.my_list.insert(1, 'a') # Inserts 'a' at index 1 -
remove(x): Removes the first item from the list whose value is equal tox.my_list.remove(2) # Removes the first occurrence of 2 -
pop([i]): Removes and returns the item at the given positioniin the list. If no index is specified,pop()removes and returns the last item in the list.last_item = my_list.pop() # Removes and returns the last item -
clear(): Removes all items from the list.my_list.clear() -
index(x[, start[, end]]): Returns the index of the first item whose value is equal tox. Raises aValueErrorif not found.index_of_3 = my_list.index(3) -
count(x): Returns the number of timesxappears in the list.count_of_2 = my_list.count(2) -
sort(key=None, reverse=False): Sorts the items of the list in place (the arguments can be used for sorting order).my_list.sort() -
reverse(): Reverses the elements of the list in place.my_list.reverse()
These methods provide a variety of ways to manipulate lists in Python.
