List Methods
Example:
Add an element to the fruits
list:
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.append(“orange”)
Output:
[‘apple’, ‘banana’, ‘cherry’, ‘orange’]
Python has a set of built-in methods that you can use on lists.
Method | Syntax | Description |
---|---|---|
append() | list.append(elmnt) | Adds an element at the end of the list |
clear() | list.clear() | Removes all the elements from the list |
copy() | list.copy() | Returns a copy of the list |
count() | list.count(value) | Returns the number of elements with the specified value |
extend() | list.extend(iterable) | Add the elements of a list (or any iterable), to the end of the current list |
index() | list.index(elmnt) | Returns the index of the first element with the specified value |
insert() | list.insert(pos, elmnt) | Adds an element at the specified position |
pop() | list.pop(pos) | Removes the element at the specified position |
remove() | list.remove(elmnt) | Removes the item with the specified value |
reverse() | list.reverse() | Reverses the order of the list |
sort() | list.sort(reverse=True|False, key=myFunc) | Sorts the list |